![](/img/trans.png)
[英]Python:how do you append the value of a dictionary key in a list and not the reference?
[英]How do you make a value from one dictionary the key for a new dictionary in python?
所以說我有字典
dict{int: tuple(int, str)}
我想用以下格式制作一個新字典
dict{str: dict{int: int}}
所以這是我想要得到的一個例子:
d1 = {
1: (22, 'this is a phrase'),
2: (333, 'here is a sentence')
}
通過一個函數,我需要能夠操縱第一個字典來獲得第二個字典:
d2 = {
'this is a phrase': {1: 22},
'here is a sentence': {2: 333},
}
對於最初的格式錯誤以及對我要獲取的內容的瘋狂描述,我深表歉意。 我只需要關於如何獲取值以成為第二個字典的鍵的簡單描述。 我希望這更加清楚!
假設數據順序與您的問題相同,則可以執行以下操作:
d1 = {
1: (22, 'this is a phrase',['apple', 'grape']),
2: (333, 'here is a sentence',['grape', 'cherry'])
}
d2 = {}
for key, values in d1.items():
for food in values[-1]:
if food not in d2:
d2[food] = {}
d2[food][values[0]] = [values[1]]
print d2
# Output: {'cherry': {333: ['here is a sentence']}, 'grape': {333: ['here is a sentence'], 22: ['this is a phrase']}, 'apple': {22: ['this is a phrase']}}
d2 = {}
# we loop through all key: value pairs in the dict
for k, v in d1.items():
# we unpack the tuple here
num, newkey = v
# we then create a new entry for the newkey if it does not exist
if newkey not in d2:
d2[newkey] = {}
d2[newkey][k] = num
這產生了
{'this is a phrase': {1: 22}, 'here is a sentence': {2: 333}}
編輯以適應問題中已更改的要求。
遍歷d1
的鍵以獲取要反匯編的值。 對於每個值,遍歷數組value[2]
,並在每個項目下的d2
插入{value[0], value[1]}
。 將d1[k1]
分配給一個臨時變量可以使其更易於閱讀:
d2 = {}
for k1 in d1.keys():
item = d1[k1]
for k2 in item[2]:
if k2 in d2:
d2[k2].append({item[0]: item[1]})
else:
d2[k2] = [{item[0]: item[1]}]
注意,在嘗試追加之前,我們檢查密鑰是否在d2
。 否則,Python將嘗試獲取d2[k2]
並在k2
不存在時拋出KeyError
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.