我有一个数组(Arr []),对于数组中的每个项目,我都希望它通过字典(specs {})并计算相应的值并将其存储在新字典中,但是请确定如何为这个新字典指定键和值{结果{})。
Arr=["saucer", "shoes"]
def calc(Arr, context, user_results):
results = {}
for x in Arr:
if x == specs.keys():
results = specs.values
results.append(x : results)
return results
specs = {'cup': 3,'saucer': 5, 'bag': 17, 'shoes': 9}
results = {“ saucer”:5,“ shoes”:9}
答案 0 :(得分:4)
您可以使用dict
中的项目使用dict
理解来构建新的specs
results = {key: specs[key] for key in Arr if key in specs}
答案 1 :(得分:1)
In [9]: specs = {'cup': 3,'saucer': 5, 'bag': 17, 'shoes': 9}
In [10]: Arr=["saucer", "shoes"]
In [11]: R = {k: v for k, v in specs.items() if k in Arr}
In [12]: R
Out[12]: {'saucer': 5, 'shoes': 9}
答案 2 :(得分:0)
输入:
Arr=["saucer", "shoes"]
specs = {'cup': 3,'saucer': 5, 'bag': 17, 'shoes': 9}
代码1:
results = {item: specs.get(item, None) for item in Arr if item in specs}
代码2:
results = {key: value for key, value in specs.items() if key in Arr}
结果:
{'saucer': 5, 'shoes': 9}
答案 3 :(得分:0)
只需检查列表并创建另一个字典
specs = {'cup': 3,'saucer': 5, 'bag': 17, 'shoes': 9}
Arr= ["saucer", "shoes"]
em={}
for item in Arr:
if item in specs:
em[item] = specs[item]
print(em)
{'saucer': 5, 'shoes': 9}
答案 4 :(得分:0)
您可以使用函数itemgetter
从字典中获取值,并使用zip
arr
列表中的值来构建新字典:
from operator import itemgetter
arr = ["saucer", "shoes"]
specs = {'cup': 3, 'saucer': 5, 'bag': 17, 'shoes': 9}
dict(zip(arr, itemgetter(*arr)(specs)))
# {'saucer': 5, 'shoes': 9}