簡體   English   中英

將給定鍵的值替換為 Python 字典中另一個給定鍵的值

[英]Replace value of a given key with value of another given key in Python Dictionary

我有一本像

dict = { '12' : '5+2',
         '5' : 'xyz',
         '2' : 'abc' }

所以我希望更新的字典像

dict = { '12' : 'xyz+abc',
         '5' : 'xyz',
         '2' : 'abc' }

注意:我知道鍵“12”的值包含“5”和“2”,因此不需要迭代,我只想用 xyz 替換 5,用 abc 替換 2。 請建議。

您只需進行鏈式重新分配:

dict['<key2>'], dict['<key1>'] = dict['<key1>'], dict['<key2>']

那是交換操作。

它也應該可以連接由其鍵引用的字典值。 在你的情況下:

dict1['12'] =  dict1['5'] + "+" + dict1['2']

另外,我建議您不要使用 python 關鍵字,如“dict”作為變量名。

我會在字典理解中使用正則表達式:

dic = {'12' : '5+2', '5' : 'xyz', '2' : 'abc'}

import re

# create the regex from the keys
# use the longer strings first to match "12" before "2"
pattern = '|'.join(map(re.escape, sorted(dic, key=lambda x: -len(x))))
# '12|5|2'

out = {k:re.sub(pattern, lambda m: dic.get(m.group()), v) for k,v in dic.items()}

Output:

{'12': 'xyz+abc', '5': 'xyz', '2': 'abc'}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM