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

标签 python dictionary

这个问题在这里已经有了答案:





Copying a key/value from one dictionary into another

(2 个回答)


去年关闭。




假设我有一本字典:

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

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

最佳答案

最简单的方法是这样的:

new_dict["color"] = mydict["color"]

但是,如果您需要传递给新字典的项目列表更大,则可以使用以下内容:
items = ["color", "fruit"]
for item in items:
    new_dict[item] = mydict[item]

关于python - 如何在python中将一个键对值从一个字典复制到另一个字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61401885/

相关文章:

Python Matplotlib : Just the graph image

python - 使用列表字典的元素

python - 如何使用 Pandas 替换 DataFrame 中的列条目并创建字典新旧值

java - 如果映射的键已知,如何提取映射中列表的大小?

Python:使用 pandas 将一个数组连接到另一个数组

Python:并非所有参数都在字符串格式化期间转换

python - 从列转换为日期时间

python - SharePoint Online 中的远程身份验证

c++ - 如何以特定方式在 C++ STL 中查找?

python - 将函数映射到字典中指定键的值