我有一个字典,每个键都有两个值,例如:
my_dict = {'Stock A': (100, 0.5), 'Stock B': (20, 0.9), 'Stock C': (40, 0.75), 'Stock D': (45, 0.3)}
我想做的是,如果两个值都满足特定要求,则返回字典键。假设我希望每个键的第一位值为OVER 30,第二位为UNDER 0.6。这两个条件都需要满足才能返回密钥。因此,在这种情况下,我希望将退回库存A和库存D。我很乐意单独打印掉键,但是如果有一种方法可以用键和两个值附加一个新的字典,那将很棒。由于我对字典的了解是不完整的,我的价值观没有标题,它们只是价值观,只是使事情变得更加艰辛。
我设想使用的代码类似于:
if value in my_dict > 30 and second value in my_dict < 0.6:
new_dict.append(key: value, second value)
我为这种尝试完全不准确而感到尴尬,但是我只是不知道如何解决这一尝试。
答案 0 :(得分:1)
尝试此代码
my_dict = {'Stock A': (100, 0.5), 'Stock B': (20, 0.9), 'Stock C': (40, 0.75), 'Stock D': (45, 0.3)}
new={}
for (stock,values) in my_dict.items():
first=values[0]
second=values[1]
if (first>30 and second<0.6):
new[name]=(first,second)
希望有帮助
答案 1 :(得分:1)
您需要使用.items()遍历字典,然后可以将元组解压缩为2个变量(firstVal
,secondVal
):
my_dict = {'Stock A': (100, 0.5), 'Stock B': (20, 0.9), 'Stock C': (40, 0.75), 'Stock D': (45, 0.3)}
new_dict = {}
for key, v in my_dict.items():
firstVal, secondVal = v
if firstVal > 30 and secondVal < 0.6:
new_dict[key] = v
print new_dict
打印:
{'Stock D': (45, 0.3), 'Stock A': (100, 0.5)}
答案 2 :(得分:0)
您可以使用dict理解来创建新的dict。
my_dict = {'Stock A': (100, 0.5), 'Stock B': (20, 0.9), 'Stock C': (40, 0.75), 'Stock D': (45, 0.3)}
new_dict = {k:v for k,v in my_dict.items() if v[0]>30 and v[1] <0.6}
print (new_dict)
结果:
{'Stock A': (100, 0.5), 'Stock D': (45, 0.3)}
答案 3 :(得分:0)
my_dict = {'Stock A': (100, 0.5), 'Stock B': (20, 0.9), 'Stock C': (40, 0.75), 'Stock D': (45, 0.3)}
result={key:value for key,value in my_dict.items() if value[0]>30 and value[1]<.6}
print(result)
输出:
{'Stock A': (100, 0.5), 'Stock D': (45, 0.3)}
答案 4 :(得分:0)
my_dict = {'Stock_A': (100, 0.5), 'Stock B': (20, 0.9), 'Stock C': (40, 0.75), 'Stock D': (45, 0.3)}
new_dict = {} # Dictionary in which the TRUE conditions are stores
# Function which makes the comparison
def comp(Val1,Val2):
Values = [30,0.6]
if Val1 > Values[0] and Val2 < Values[1]:
return True,(Val1,Val2)
else:
return False,None
# Creates the new dictionary
for key in my_dict:
Res = comp(my_dict[key][0],my_dict[key][1])
if Res[0]:
new_dict[key] = Res[1]
print(new_dict)
{'Stock_A': (100, 0.5), 'Stock D': (45, 0.3)}
答案 5 :(得分:-2)
使用dictionary
创建此list comprehensions
-
my_dict = {'Stock A': (100, 0.5), 'Stock B': (20, 0.9), 'Stock C': (40, 0.75), 'Stock D': (45, 0.3)}
my_dict_out = dict([ (k,r) for k,r in my_dict.items() if r[0]>30 and r[1] <0.6])
print(my_dict_out)
{'Stock A': (100, 0.5), 'Stock D': (45, 0.3)}
注意:这个答案被标记为negative
了很多次,因为我使用.iteritems()
而不是.items()
,并且对{{ 1}}。因此,如果您使用的是Python 3.+
,请使用Python 2.+
,否则使用.iteritems()
。