更新 python 字典(向现有键添加另一个值)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41825868/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 01:40:32  来源:igfitidea点击:

Update python dictionary (add another value to existing key)

python

提问by jundymek

I have simple dictionary with key, value:

我有一个带键值的简单字典:

d = {'word': 1, 'word1': 2}

I need to add another value (to make a list from values):

我需要添加另一个值(从值中创建一个列表):

d = {'word': [1, 'something'], 'word1': [2, 'something1']}

I can't deal with it. Any clues?

我无法处理。有什么线索吗?

回答by Willem Van Onsem

Well you can simply use:

那么你可以简单地使用:

d['word'] = [1,'something']

Or in case the 1needs to be fetched:

或者如果1需要获取:

d['word'] = [d['word'],'something']

Finally say you want to update a sequence of keys with new values, like:

最后说你想用新值更新一系列键,比如:

to_add = {'word': 'something', 'word1': 'something1'}

you could use:

你可以使用:

for key,val in to_add.items():
    if key in d:
        d[key] = [d[key],val]

回答by u1860929

You could write a function to do this for you:

您可以编写一个函数来为您执行此操作:

>>> d = {'word': 1, 'word1': 2}
>>> def set_key(dictionary, key, value):
...     if key not in dictionary:
...         dictionary[key] = value
...     elif type(dictionary[key]) == list:
...         dictionary[key].append(value)
...     else:
...         dictionary[key] = [dictionary[key], value]
... 
>>> set_key(d, 'word', 2)
>>> set_key(d, 'word', 3)
>>> d
{'word1': 2, 'word': [1, 2, 3]}

Alternatively, as @Dan pointed out, you can use a list to save the data initially. A Pythonic way if doing this is you can define a custom defaultdict which would add the data to a list directly:

或者,正如@Dan 指出的那样,您可以使用列表来最初保存数据。如果这样做,Pythonic 的方法是您可以定义一个自定义 defaultdict,它将数据直接添加到列表中:

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> d[1].append(2)
>>> d[2].append(2)
>>> d[2].append(3)
>>> d
defaultdict(<type 'list'>, {1: [2], 2: [2, 3]})

回答by Dan

It will be easiest if you always use lists, even when you just have a single value. It will just be a list of length 1.

如果您始终使用列表,那将是最简单的,即使您只有一个值。它只是一个长度为 1 的列表。

>>> d = {'a': [1], 'b': [2]}
>>> d
{'a': [1], 'b': [2]}
>>>
>>> d['a'].append(5)
>>> d
{'a': [1, 5], 'b': [2]}

回答by Mario

You can create your dictionary assigning a list to each key

您可以创建字典,为每个键分配一个列表

d = {'word': [1], 'word1': [2]}

and then use the following synthases to add any value to an existing key or to add a new pair of key-value:

然后使用以下合成酶向现有键添加任何值或添加新的键值对:

d.setdefault(@key,[]).append(@newvalue)

For your example will be something like this:

对于您的示例将是这样的:

d = {'word': [1], 'word1': [2]}
d.setdefault('word',[]).append('something')
d.setdefault('word1',[]).append('something1')
d.setdefault('word2',[]).append('something2')   
print(d)
{'word': [1, 'something'], 'word1': [2, 'something1'], 'word2': ['something2']}

回答by jundymek

Thanks for help. I did it that way (thanks to Willem Van Onsem advice):

感谢帮助。我是这样做的(感谢 Willem Van Onsem 的建议):

x = (dict(Counter(tags))) #my dictionary
for i in x:
    color = "#%06x" % random.randint(0, 0xFFFFFF)
    x[i] = [x[i], color]

回答by user11109376

This is what I would do. I hope it helps. If you have a lot of items to add to your dictionary this may not be the fastest route.

这就是我要做的。我希望它有帮助。如果您有很多项目要添加到字典中,这可能不是最快的路线。

d = {'word':1, 'word1':2}

d['word']=[1, 'something']

d['word1']=[2, 'something1']

print(d)

{'word': [1, 'something'], 'word1': [2, 'something1']} 

回答by Abhijit

you could try the below:

你可以试试下面的:

d['word'] = [1, 'something']

d['word'] = [1, 'something']

d['word1'] = [2, 'something']

d['word1'] = [2, 'something']

call dnow

d现在打电话

Hope this helps!

希望这可以帮助!