Saya sangat baru dalam pengkodean dan saya mencoba untuk beralih melalui daftar dan membuat kamus tunggal dengan kunci yang sama. Kode saya saat ini sedang membuat sekitar 1000 kamus dalam format yang benar dengan kunci yang sama, tetapi saya tidak tahu bagaimana membuatnya menjadi satu kamus.

for salaries, match in matching_salaries_non_employees.items():

   final_match.update(matches)

   Power_match = (match['Status']['Power'])+ ": " + (salaries)
    
   Length_match = (match['Status']['Length'])+ ": " + (match['Break']['Temp'])
        
   duration_Status = (match ['Status'][str('duration')])
   duration_Break = (match ['Break']['duration'])
   duration_match = (str(duration_Status) + ': ' + str(duration_Break))
    
   freq_Status = (match ['Status'][str('freq')])
   freq_Break = (match ['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]}

Contoh bagian dari output saya terlihat seperti;

{'Power': ['high: high'], 'Length': ['Long: Short'], 'Duration': ['2.22: 1.01'], 'Freq': ['0.081229: 0.079503'], 'Start Times': ['10.10.08: 11.09.16']}
{'Power': ['med-high: med-high'], 'Length': ['Long: Long'], 'Duration': ['1.16: 0.81'], 'Freq': ['0.0988: 0.565'], 'Start Times': ['17.08.98: 31:01:03']}

Padahal saya maunya digabung jadi satu kamus ini biar bisa saya simpan ke dalam satu file csv

1
emilyxyzzyx 22 September 2021, 02:35

2 jawaban

Jawaban Terbaik

Solusi termudah dan paling mudah adalah dengan menggunakan defaultdict

from collections import defaultdict

matches = defaultdict(list)

for salaries, match in matching_salaries_non_employees.items():

   Power_match = (match['Status']['Power'])+ ": " + (salaries)
    
   Length_match = (match['Status']['Length'])+ ": " + (match['Break']['Temp'])
        
   duration_Status = (match ['Status'][str('duration')])
   duration_Break = (match ['Break']['duration'])
   duration_match = (str(duration_Status) + ': ' + str(duration_Break))
    
   freq_Status = (match ['Status'][str('freq')])
   freq_Break = (match ['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)
1
ShadowRanger 22 September 2021, 01:01

Jawaban oleh @Matias Cicero bagus, tetapi inisialisasi eksplisit juga sangat sederhana:

keys = ['Power', 'Length', 'Duration', 'Freq', 'Start Times']
matches = {k: [] for k in keys}

Yang akan menggantikan garis

from collections import defaultdict
matches = defaultdict(list)
0
ATony 22 September 2021, 00:51