在Python中将字典插入字典

时间:2013-05-01 00:31:43

标签: python dictionary insert

我有这样的字典:

dict1={'a':4,'d':2}

我有一个这样的词典列表:

diclist=[{'b':3,'c':3},{'e':1,'f':1}]

作为输出,我想让dict1像这样:

dict1={'a':4,'b':3,'c':3,'d':2,'e':1,'f':1}

所以,我需要

  1. 将dict1的值与diclist的值进行比较
  2. 如果diclist中的dict值小于dict1中的dict,请将dict插入dict1
  3. 在diclist中迭代2
  4. 这可能很容易,但是,如果您愿意为此提供帮助,我们将不胜感激。

3 个答案:

答案 0 :(得分:1)

由于您的示例中的键都是唯一的,因此它与仅合并所有词组有什么不同?

dict1 = {'a': 4, 'd': 2}
diclist = [{'b': 3, 'c': 3}, {'e': 1, 'f': 1}]
for d in diclist:
    dict1.update(d)

这是一般方法。考虑将来提供更全面的例子

>>> dict1={'a':4,'d':2}
>>> diclist=[{'b':3,'c':3},{'e':1,'f':1}]
>>> 
>>> for d in diclist:
...  for k, v in d.items():
...   if k not in dict1 or v < dict1[k]:
...    dict1[k] = v
... 
>>> dict1
{'a': 4, 'c': 3, 'b': 3, 'e': 1, 'd': 2, 'f': 1}

答案 1 :(得分:0)

for d in diclist:  # iterate over the dicts
    for k, v in d.items():  # iterate over the elements
         v2 = dict1.set_default(k, v)  # set the value if the key does not exist
                                       # and return the value (existing or newly set)
         if v < v2:  # compare with the existing value and the new value
             dict1[k] = v

这可能是最简洁和可读的。

答案 2 :(得分:0)

这样的事情:

In [15]: dict1={'a':4,'d':2}

In [16]: diclist=[{'b':3,'c':3},{'e':1,'f':1}]

In [17]: for dic in diclist:
    for key,value in dic.items():
        val=dict1.get(key,float("inf")) #fetch the value from dict1 if key is not found then return infinity
        if value < val:
            dict1[key] = value

In [18]: dict1
Out[18]: {'a': 4, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 1}