我是一個編碼新手,我正試圖通過一個串列進行迭代,并創建一個具有相同鍵值的單一字典。我的代碼目前正在以正確的格式創建大約 1000 個具有相同鍵的字典,但我不知道如何將這些字典變成一個字典。
for salaries, match in matching_salaries_non_employees.items():
final_match.update(matches)
Power_match = (match['Status']['Power']) " 。" (工資)
Length_match = (match['Status']['Length']) " 。" (match['break']['Temp'])
duration_Status = (match ['Status'][str('duration') ])
duration_Break = (匹配 ['Break']['duration'])
duration_match = (str(duration_Status) ': ' str(duration_Break)
freq_Status = (match ['Status'][str('freq') ]
freq_Break = (匹配 ['Break']['freq'])
freq_match = (str(freq_Status) " 。" str(freq_Break))
start_times = (match['Status']['start time']) ": " (match['break']['start time'])
matches = {'Power': [power_match], 'Length': [Length_match], 'Duration': [duration_match], 'Freq': [freq_match], 'Start Times': [start_times]}
我的輸出的一部分的例子看起來像;
{'Power': ['high: high'], 'Length': ['Long: Short'], 'Duration': ['2.22: 1.01'], 'Freq': ['0.081229: 0.079503'], '起始時間': ['10.10.08: 11.09.16']}.
{'Power': ['med-high: med-high'], '長度': ['Long: Long'], 'Duration': ['1.16: 0.81'], 'Freq': ['0.0988: 0.565'], '起始時間': ['17.08.98: 31:01:03']}。
而我想把它合并成一個字典,這樣我就可以把它保存到一個csv檔案中
uj5u.com熱心網友回復:最簡單和最直接的解決方案是使用一個defaultdict
from collections import defaultdict
matches = defaultdict(list)
for salaries, match in matching_salaries_non_employees.items()。
Power_match = (match['Status']['Power']) " 。" (工資)
Length_match = (match['Status']['Length']) " 。" (match['break']['Temp'])
duration_Status = (match ['Status'][str('duration') ])
duration_Break = (匹配 ['Break']['duration'])
duration_match = (str(duration_Status) ': ' str(duration_Break)
freq_Status = (match ['Status'][str('freq') ]
freq_Break = (匹配 ['Break']['freq'])
freq_match = (str(freq_Status) " 。" str(freq_Break))
start_times = (match['Status']['start time']) ": " (match['break']['start time'])
matches['Power'].append(Power_match)
matches['Length'].append(Length_match)
matches['Duration'].append(Duration_match)
matches['Freq'].append(freq_match)
matches['Start Times'].append(start_times)
uj5u.com熱心網友回復:
@Matias Cicero的答案很好,但顯式初始化也很簡單:
keys = ['Power', 'Length', '持續時間', '頻率', '開始時間']
匹配 = {k: [] for k in keys}。
這將取代這幾行字
from collections import defaultdict
matches = defaultdict(list)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/331571.html
標籤:
