Python|使用列表内容创建字典
有时我们需要处理以列表格式传入的数据,并将列表转换为字典格式。当我们处理机器学习以提供更改格式的进一步输入时,这个特殊问题很常见。让我们讨论这种相互转换发生的某些方式。
方法 #1:使用字典理解 + zip()
在这种方法中,我们使用字典推导来执行迭代和逻辑部分,将所有列表绑定到一个字典中,并通过 zip函数完成关联键。
# Python3 code to demonstrate
# Dictionary creation using list contents
# using Dictionary comprehension + zip()
# initializing list
keys_list = ["key1", "key2"]
nested_name = ["Manjeet", "Nikhil"]
nested_age = [22, 21]
# printing original lists
print("The original key list : " + str(keys_list))
print("The original nested name list : " + str(nested_name))
print("The original nested age list : " + str(nested_age))
# using Dictionary comprehension + zip()
# Dictionary creation using list contents
res = {key: {'name': name, 'age': age} for key, name, age in
zip(keys_list, nested_name, nested_age)}
# print result
print("The dictionary after construction : " + str(res))
The original key list : [‘key1’, ‘key2’]
The original nested name list : [‘Manjeet’, ‘Nikhil’]
The original nested age list : [22, 21]
The dictionary after construction : {‘key1’: {‘age’: 22, ‘name’: ‘Manjeet’}, ‘key2’: {‘age’: 21, ‘name’: ‘Nikhil’}}
方法 #2:使用字典理解 + enumerate()
可以使用由 zip函数执行的enumerate
函数来执行类似的任务。字典理解执行与上述类似的任务。
# Python3 code to demonstrate
# Dictionary creation using list contents
# using dictionary comprehension + enumerate()
# initializing list
keys_list = ["key1", "key2"]
nested_name = ["Manjeet", "Nikhil"]
nested_age = [22, 21]
# printing original lists
print("The original key list : " + str(keys_list))
print("The original nested name list : " + str(nested_name))
print("The original nested age list : " + str(nested_age))
# using dictionary comprehension + enumerate()
# Dictionary creation using list contents
res = {val : {"name": nested_name[key], "age": nested_age[key]}
for key, val in enumerate(keys_list)}
# print result
print("The dictionary after construction : " + str(res))
The original key list : [‘key1’, ‘key2’]
The original nested name list : [‘Manjeet’, ‘Nikhil’]
The original nested age list : [22, 21]
The dictionary after construction : {‘key1’: {‘age’: 22, ‘name’: ‘Manjeet’}, ‘key2’: {‘age’: 21, ‘name’: ‘Nikhil’}}