简体   繁体   English

在python字典中插入或更新键

[英]insert or update keys in a python dictionary

I have a python dictionary dict1 with more than 20,000 keys and I want to update it with another dictionary dict2 . 我有一个python字典dict1超过20,000键,我想用另一个字典dict2 update它。 The dictionaries look like this: 字典看起来像这样:

dict1
  key11=>[value11]
  key12=>[value12]
  ...
  ...
  keyxyz=>[value1x]      //common key
  ...... so on

dict2
  key21=>[value21]
  key22=>[value22]
  ...
  ...
  keyxyz=>[value2x]      // common key
  ........ so on

If I use 如果我使用

dict1.update(dict2)

then the keys of dict1 which are similar to keys of dict2 will have their values overwritten by values of dict2 . 随后的键dict1这是类似的按键dict2会通过的值覆盖它们的值dict2 What I want is if a key is already present in dict1 then the value of that key in dict2 should be appended to value of dict1. 我想要的是如果一个键已经存在于dict1中,那么dict2中该键的值应该附加到dict1的值。 So 所以

dict1.conditionalUpdate(dict2)

should result in 应该导致

dict1
  key11=>[value11]
  key12=>[value12]
  key21=>[value21]
  key22=>[value22]
  ...
  ...
  keyxyz=>[value1x,value2x]

A naive method would be iterating over keys of dict2 for each key of dict1 and insert or update keys. 幼稚的方法是迭代的键dict2对的每个键dict1和插入或更新的密钥。 Is there a better method? 有更好的方法吗? Does python support a built in data structure that supports this kind of functionality? python是否支持支持这种功能的内置数据结构?

Use defaultdict from the collections module. 使用collections模块中的defaultdict

>>> from collections import defaultdict
>>> dict1 = {1:'a',2:'b',3:'c'}
>>> dict2 = {1:'hello', 4:'four', 5:'five'}
>>> my_dict = defaultdict(list)
>>> for k in dict1:
...    my_dict[k].append(dict1[k])
...
>>> for k in dict2:
...    my_dict[k].append(dict2[k])
...
>>> my_dict[1]
['a', 'hello']

This is actually pretty simple to do using a dict comprehension and itertools.groupby() : 使用dict理解和itertools.groupby()实际上非常简单:

dict1 = {1: 1, 2: 2, 3: 3, 4: 4}
dict2 = {5: 6, 7: 8, 1: 1, 2: 2}

from itertools import groupby, chain
from operator import itemgetter

sorted_items = sorted(chain(dict1.items(), dict2.items()))

print({key: [value[1] for value in values] for key, values in groupby(sorted_items, itemgetter(0))})

Gives us: 给我们:

{1: [1, 1], 2: [2, 2], 3: [3], 4: [4], 5: [6], 7: [8]}

Naturally, this creates a new dict, but if you need to update the first dict, you can do that trivially by updating with the new one. 当然,这会创建一个新的dict,但是如果你需要更新第一个dict,你可以通过更新新的dict来做到这一点。 If your values are already lists, this may need some minor modification (but I presume you were doing that for the sake of the operation, in which case, there is no need). 如果你的值已经是列表,这可能需要一些小修改(但我认为你是为了操作而这样做,在这种情况下,没有必要)。

Naturally, if you are using Python 2.x, then you will want to use dict.viewitems() or dict.iteritems() over dict.items() . 当然,如果你正在使用Python 2.x的,那么你将要使用dict.viewitems()dict.iteritems()dict.items() If you are using a version of Python prior to dict comprehensions, then you could use dict((key , value) for ...) instead. 如果你在dict理解之前使用的是Python版本,那么你可以使用dict((key , value) for ...)代替dict((key , value) for ...)

Another method without importing anything, just with the regular Python dictionary: 没有导入任何东西的另一种方法,只需使用常规Python字典:

>>> dict1 = {1:'a',2:'b',3:'c'}
>>> dict2 = {1:'hello', 4:'four', 5:'five'}
>>> for k in dict2:
...  dict1[k] = dict1.get(k,"") + dict2.get(k)
... 
>>> dict1
{1: 'ahello', 2: 'b', 3: 'c', 4: 'four', 5: 'five'}
>>> 

dict1.get(k,"") returns the value associated to k if it exists or an empty string otherwise, and then append the content of dict2 . dict1.get(k,"")返回与k相关联的值(如果存在)或否则返回空字符串,然后追加dict2的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM