2013-05-01 77 views
0

字典我有這樣一本字典:插入詞典在Python

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一個字典的值大於dict1的一個小,插入字典內dict1
  3. 迭代2 diclist

這可能是不過,如果你願意爲此提供幫助,我們將不勝感激。

回答

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} 
+0

我認爲你需要實現的合併策略來解決_if在diclist一個字典的值大於dict1的一個小,插入字典內dict1_ – 2013-05-01 00:36:42

+0

這似乎缺少第2點的條件 – Johnsyweb 2013-05-01 00:36:47

+0

@ hd1合併策略對於有序列表和集合(例如字典)是必需的當用戶在衝突(兩個合併字典之間的相同鍵)發生時在規範2中指定了他想要合併策略的內容 – 2013-05-01 01:13:23

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 

這可能是最簡明易讀,提供更全面的例子。

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}