将键/值从一个字典复制到另一个 [英] Copying a key/value from one dictionary into another

查看:233
本文介绍了将键/值从一个字典复制到另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字典(大致),如下所示:{'UID': 'A12B4', 'name': 'John', 'email': 'hi@example.com}

I have a dict with main data (roughly) as such: {'UID': 'A12B4', 'name': 'John', 'email': 'hi@example.com}

我还有另一个像这样的字典:{'UID': 'A12B4', 'other_thing: 'cats'}

and I have another dict like: {'UID': 'A12B4', 'other_thing: 'cats'}

我不清楚如何加入"两个字典,然后将"other_thing"放入主字典.我需要的是:{'UID': 'A12B4', 'name': 'John', 'email': 'hi@example.com, 'other_thing': 'cats'}

I'm unclear how to "join" the two dicts to then put "other_thing" to the main dict. What I need is: {'UID': 'A12B4', 'name': 'John', 'email': 'hi@example.com, 'other_thing': 'cats'}

我对这样的理解还很陌生,但是我的直觉说必须要有一条直截了当的方法.

I'm pretty new to comprehensions like this, but my gut says there has to be a straight forward way.

推荐答案

您要使用dict.update方法:

d1 = {'UID': 'A12B4', 'name': 'John', 'email': 'hi@example.com'}
d2 = {'UID': 'A12B4', 'other_thing': 'cats'}
d1.update(d2)

输出:

{'email': 'hi@example.com', 'other_thing': 'cats', 'UID': 'A12B4', 'name': 'John'}

文档:

使用其他键/值对更新字典,覆盖现有键.不返回任何内容.

Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None.

这篇关于将键/值从一个字典复制到另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆