我想比較字典中的鍵,以便如果有多個鍵與不同的值我可以將這些不同的值添加到該鍵。例如,假設我們有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. Python:爲字典鍵添加多個值
- 7. 比較字典值和彈出鍵
- 8. 追加到Python的字典鍵值:
- 9. 將列表值添加到字典鍵
- 10. 夫特:比較字典鍵
- 11. 途徑字典的鍵和值比較在python
- 12. Python比較字典與csr_matrices作爲值
- 13. 比較字典值在Python在同一個字典的每個鍵
- 14. 我如何添加到Python字典值使用字符串鍵
- 15. 比較Python字典和嵌套字典
- 16. 比較元組/字典python
- 17. python多個字典比較
- 18. Python Lambda比較字典
- 19. Python:比較兩個字典
- 20. 比較來自字典python的字典值
- 21. Python - 將鍵值對添加到數組中的字典
- 22. 作業:Python 3.3:將字典中的鍵和值添加到類
- 23. 將多個值添加到Python字典中的單個鍵
- 24. 用相應的鍵比較字典?
- 25. Python字典添加值
- 26. 將多個值添加到python字典
- 27. 如何比較字典鍵值和元組鍵值
- 28. 迅速比較字典值
- 29. 無法比較字典值
- 30. 基於鍵比較添加JSON值
@ Zrot25你得到這個工作? –