如何在python中将一个密钥对值从一个字典复制到另一个字典中

问题描述 投票:0回答:2

假设我有字典:

mydict = {"color":"green",
          "type":"veg",
          "fruit":"apple",
          "level": 5
          }
new_dict = {}

我想将键“颜色”和“水果”及其值附加到new_dict中。最简单的方法是什么?谢谢。

python dictionary
2个回答
1
投票

您可以尝试以下方法:

new_dict = {x:mydict[x] for x in mydict if x in ('color','fruit')}

0
投票

您可以保留一组要添加的键,然后用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'}
© www.soinside.com 2019 - 2024. All rights reserved.