假设我有字典:
mydict = {"color":"green",
"type":"veg",
"fruit":"apple",
"level": 5
}
new_dict = {}
我想将键“颜色”和“水果”及其值附加到new_dict
中。最简单的方法是什么?谢谢。
您可以尝试以下方法:
new_dict = {x:mydict[x] for x in mydict if x in ('color','fruit')}
您可以保留一组要添加的键,然后用dict理解过滤掉键:
>>> mydict = {"color":"green",
... "type":"veg",
... "fruit":"apple",
... "level": 5
... }
>>> keys = {"color", "fruit"}
>>> new_dict = {k: v for k, v in mydict.items() if k in keys}
>>> new_dict
{'color': 'green', 'fruit': 'apple'}