2017-10-15 25 views
0

我想比較字典中的鍵,以便如果有多個鍵與不同的值我可以將這些不同的值添加到該鍵。例如,假設我們有dict {'a':'b','b':'c','c':'d'}並且我添加了{'a':'c'}我想知道如何改變字典,以便它現在是dict {'a':'bc','b':'c','c':'d'}比較字典的鍵添加到值 - Python

回答

0

要使整個過程起作用,您應該嘗試寫一些碼。這裏有一些啓發,讓你開始。

首先,你需要能夠通過Python字典遍歷並獲得所有的鍵和值依次爲:

for key, value in new_dict.items(): 

好了,這是非常有用的。

接下來,我們需要一種方法來知道新密鑰是否將在舊字典中。我們有兩種方式,在這裏做:

for key, value in new_dict.items(): 
    if key in old_dict: 
     write some code that goes here 
    else: 
     write some alternate code here for when key isn't in the dict 

或者,我們可以這樣做:

for key, value in new_dict.items(): 
    old_dict_key_val = old_dict.get(key) 
    if old_dict_key_val is not None: 
     write some code that goes here 
    else: 
     write some alternate code here for when key isn't in the dict 

對於所有意圖和目的,這些都是幾乎等同。這應該足以讓你開始!之後,如果您遇到困難,您可以回到這裏並提出具體問題。

祝你好運自己寫一些代碼來解決這個問題!

0

使用try/except,但非常緊湊和Pythonic的一點點非傳統。

big_dict = {'a':'b','b':'c','c':'d'} 
little_dict = {'a':'c'} 

for key, value in little_dict.items(): 
    try: 
     big_dict[key] += value 
    except KeyError: 
     big_dict[key] = value 
+0

@ Zrot25你得到這個工作? –

0

您可以從包裝圖爾茨(https://toolz.readthedocs.io/en/latest/index.html)使用純函數merge_with

該函數的工作方式如下:(1)函數將使用同一個鍵的不同字典中的值以及(2)要合併的字典。

from toolz import merge_with 

d1 = {'a':'i','b':'j'} 
d2 = {'a':'k'} 

def conc(a): 
    return ''.join(a) 

a = merge_with(conc,d1,d2) 

>>> {'a': 'ik', 'b': 'j'} 
0

使用defaultdict

from collections import defaultdict 

d = defaultdict(str) 
d.update({'a': 'b','b': 'c','c': 'd'}) 
print(d) 
// defaultdict(<type 'str'>, {'a': 'b', 'b': 'c', 'c': 'd'}) 

d.update({'a': 'c'}) 
print(d) 
// defaultdict(<type 'str'>, {'a': 'bc', 'b': 'c', 'c': 'd'}) 
0

我居然想出了一個解決方案,我的問題感謝您的答覆 我所做的就是這樣對不起我的問題混淆。這讓我檢查關鍵是在字典中,如果這樣我就可以添加值是關鍵的一起

for x in range(len(word)) 
    key = word[x] 
    if key in dict: 
     dict[word[x]] = [word[x+1] + dict[word[x]] 
    else: 
     dict[word[x] = word[x+1]