我想比较字典中的键,以便如果有多个键与不同的值我可以将这些不同的值添加到该键。例如,假设我们有dict {'a':'b','b':'c','c':'d'}并且我添加了{'a':'c'}我想知道如何改变字典,以便它现在是dict {'a':'bc','b':'c','c':'d'}比较字典的键添加到值 - Python
0
A
回答
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
您可以从包装图尔茨(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]
相关问题
- 1. python - 比较值与字典
- 2. 比较字典(Python)
- 3. Python字典比较
- 4. Python字典比较
- 5. Python:为字典键添加多个值
- 6. 比较字典值和弹出键
- 7. 追加到Python的字典键值:
- 8. 将列表值添加到字典键
- 9. 夫特:比较字典键
- 10. 比较字典值在Python在同一个字典的每个键
- 11. 比较Python字典和嵌套字典
- 12. Python Lambda比较字典
- 13. 作业:Python 3.3:将字典中的键和值添加到类
- 14. 用相应的键比较字典?
- 15. 如何比较字典键值和元组键值
- 16. 迅速比较字典值
- 17. 无法比较字典值
- 18. 添加到Python字典
- 19. 如何比较带有未知键的字典的值?
- 20. 比较字典
- 21. Python字典键(它是类对象)与多个比较器的比较
- 22. 只有两个字典在python比较匹配关键字的值
- 23. Python:列表中的变量与字典键之间的比较
- 24. python的字典键/值
- 25. 如果键已经在字典中,将值添加到字典并将列表项的值增加1(python)
- 26. 比较python中的2个字典
- 27. 比较Python列表中的字典
- 28. 比较庞大的python字典列表
- 29. Python的 - 比较键
- 30. 在python比较两个字典来获得类似的关键
@ Zrot25你得到这个工作? –