我對 python 還是比較陌生,并試圖自學不同的東西。然而,這個問題讓我很頭疼。我有一個字典串列。我想SourceKey從字典中提取 的值并將該值用作串列中的新鍵,該串列還包含新鍵內的所有其余字典條目(我希望這聽起來不會太混亂)。例如:
data = [
{'AssetId':'1234',
'CreatedById':'02i3s',
'Billable__c': True,
'SourceKey': '00a1234'},
{'AssetId':'4567',
'CreatedById':'03j8t',
'Billable__c':True,
'SourceKey': '00b4321'}
]
所以現在我想從值SourceKey中創建一個字典,所以它看起來像這樣:
new_data = [
{'00a1234': {'AssetId':'1234',
'CreatedById':'02i3s',
'Billable__c': True},
{'00b4321': {'AssetId':'4567',
'CreatedById':'03j8t',
'Billable__c':True}
]
我基本上有這個起點,但我只是堅持如何將嵌套字典的鍵值對放在新值中,SourceKey因為我知道我需要___用其余的鍵值替換data:
[new_data] = {}
for row in data:
if row['SourceKey']:
new_data.update(row['SourceKey'], ___)
任何幫助都會很棒!
uj5u.com熱心網友回復:
你定義[new_data]為 dict 但你實際上想要new_data作為字典。
使用comprehension獲取沒有SourceKey的資料內容:
from pprint import pprint
data = [
{'AssetId':'1234',
'CreatedById':'02i3s',
'Billable__c': True,
'SourceKey': '00a1234'},
{'AssetId':'4567',
'CreatedById':'03j8t',
'Billable__c':True,
'SourceKey': '00b4321'}
]
new_data = dict()
for row in data:
if row['SourceKey']:
new_data[row['SourceKey']] = {k:v for k,v in row.items() if k != 'SourceKey'}
pprint(new_data)
輸出:
{'00a1234': {'AssetId': '1234', 'Billable__c': True, 'CreatedById': '02i3s'},
'00b4321': {'AssetId': '4567', 'Billable__c': True, 'CreatedById': '03j8t'}}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/328532.html
