[英]How can I create a dictionary from an unordered list, where the list contains the keys which are then followed by multiple values?
[英]How can I create a dictionary from two lists, one list is the keys, the other contains nested values?
我有兩個清單:
list_values = [['James', '40', 'Engineer'], ['Mary', '30', 'Nurse]]
和
keys = ['Name', 'Age' 'Profession']
。
我的意圖是使用以下 output 創建一個字典:
{'name': 'James', 'Age': '40', 'Profession': 'Engineer'},{'name': 'Mary', 'Age': '30', 'Profession': 'Nurse'}
但是,我的代碼只給了我生成的第一個字典中的內容,即:
{'name': 'James', 'Age': '40', 'Profession': 'Engineer'}
這是代碼:
dict_content = {}
for person in list_values:
for val in range(len(keys)):
key = keys[val]
value = person[val]
dict_content[key] = value
print(dict_content)
例如,我不知道為什么我的代碼只運行內部for loop
,而不會回來在第一個for loop
中選擇第二個嵌套列表。 我很想知道為什么我的代碼是錯誤的,因為我花了將近一天的時間試圖解決這個問題,但沒有成功。
只需一條線即可:
dct = [dict(zip(keys,vals)) for vals in list_values]
Output:
[{'Name': 'James', 'Age': '40', 'Profession': 'Engineer'}, {'Name': 'Mary', 'Age': '30', 'Profession': 'Nurse'}]
list_values = [['James', '40', 'Engineer'], ['Mary', '30', 'Nurse']]
keys = ['Name', 'Age', 'Profession']
dict = {k:[] for k in keys}
for person in list_values:
for i in range(len(keys)):
dict[keys[i]].append(person[i])
在這種情況下,可以使用pd.DataFrame.from_dict(dict)
輕松生成 dataframe 。
在 python 中,字典鍵必須是唯一的,這意味着您不能在一個字典中真正擁有多個姓名和年齡。 相反,您可以列出這些詞典。 您還可以使用zip
function 將兩個列表組合成一個字典,它返回一個包含相應索引元組的新列表。 所以zip([1, 2], [3, 4])
會返回[(1, 3), (2, 4)]
。 然后,您可以使用dict(zipped_list)
從中構造一個字典 考慮到所有這些,執行您想要的代碼是這樣的
list_values = [['James', '40', 'Engineer'], ['Mary', '30', 'Nurse']]
keys = ['Name', 'Age', 'Profession']
dict_list = [dict(zip(keys, i)) for i in list_values]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.