📜  Python - 解析字典中的浮点键

📅  最后修改于: 2022-05-13 01:54:43.171000             🧑  作者: Mango

Python - 解析字典中的浮点键

给定具有各种浮点键的字典,找到一种方法将它们作为单个值访问。

方法 #1:使用 float() + 循环

这是解决这个问题的方法之一。这里使用的策略是使用float()将key转换为float值,解析为单个值,转换为float()后对输入字符串进行检查,都解析为普通的float值。

Python3
# Python3 code to demonstrate working of 
# Resolve Float Keys in Dictionary
# Using float() + loop()
  
# initializing dictionary
test_dict = {"010.78" : "Gfg", "9.0" : "is", "10" : "Best"}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing K 
K = "10.78"
  
# performing resolution
res = dict()
for key in test_dict:
    res[float(key)] = test_dict[key]
  
# converting compare value to float 
convK = float(K)
  
# performing value access 
res = res[convK]
  
# printing result 
print("Value of resolved float Key : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Resolve Float Keys in Dictionary
# Using dictionary comprehension + float()
  
# initializing dictionary
test_dict = {"010.78" : "Gfg", "9.0" : "is", "10" : "Best"}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing K 
K = "10.78"
  
# performing resolution using dictionary comprehension
res = {float(key) : test_dict[key] for key in test_dict}
  
# converting compare value to float 
convK = float(K)
  
# performing value access 
res = res[convK]
  
# printing result 
print("Value of resolved float Key : " + str(res))


输出
The original dictionary is : {'010.78': 'Gfg', '9.0': 'is', '10': 'Best'}
Value of resolved float Key : Gfg

方法 #2:使用字典理解 + float()

这以与上述方法类似的方式计算。不同之处在于转换使用了一种线性字典理解。

Python3

# Python3 code to demonstrate working of 
# Resolve Float Keys in Dictionary
# Using dictionary comprehension + float()
  
# initializing dictionary
test_dict = {"010.78" : "Gfg", "9.0" : "is", "10" : "Best"}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing K 
K = "10.78"
  
# performing resolution using dictionary comprehension
res = {float(key) : test_dict[key] for key in test_dict}
  
# converting compare value to float 
convK = float(K)
  
# performing value access 
res = res[convK]
  
# printing result 
print("Value of resolved float Key : " + str(res)) 
输出
The original dictionary is : {'010.78': 'Gfg', '9.0': 'is', '10': 'Best'}
Value of resolved float Key : Gfg