2017-10-15 76 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]