我现在有3个列表和一个空字典:
dict = {}
name = ['Bob', 'Amy', 'Jack']
gender = ['Male', 'Female', 'Male']
car = ['kia', 'ford', 'audi']
country = ['UK', 'US', 'Australia']
我可以使用for循环来创建字典条目吗?所以理想情况下,我最终会得到:
dict = {'Bob': {'gender':'Male', 'car':'kia', 'country':'UK'},
'Amy': {'gender':'Female', 'car':'ford', 'country':'US'},
'Jack': {'gender':'Male', 'car':'audi', 'country':'Australia'}}
您可以使用zip
和dict comprehension
:
name = ['Bob', 'Amy', 'Jack']
gender = ['Male', 'Female', 'Male']
car = ['kia', 'ford', 'audi']
country = ['UK', 'US', 'Australia']
db = {name: dict(zip(['gender', 'car', 'country'], rest))
for name, *rest
in zip(name, gender, car, country)
}
print(db)
输出:
{'Bob': {'gender': 'Male', 'car': 'kia', 'country': 'UK'},
'Amy': {'gender': 'Female', 'car': 'ford', 'country': 'US'},
'Jack': {'gender': 'Male', 'car': 'audi', 'country': 'Australia'}}
解压后如下:
for data in zip(name, gender, car, country):
n, g, ca, co = data
db[n] = {
'gender' : g,
'car' : ca,
'country': co
}
如果我们看到,zip
返回什么:
>>> for data in zip(name, gender, car, country):
print(data)
('Bob', 'Male', 'kia', 'UK')
('Amy', 'Female', 'ford', 'US')
('Jack', 'Male', 'audi', 'Australia')
现在,我们可以解包这些元组(参见iterable unpacking
:
>>> n, g, ca, co = ('Bob', 'Male', 'kia', 'UK')
>>> n
'Bob'
>>> g
'Male'
>>> ca
'kia'
>>> co
'UK'
# Or we can take the name separately (as shown in dict comprehension):
>>> name, *rest = ('Bob', 'Male', 'kia', 'UK')
>>> name
'Bob'
>>> rest
['Male', 'kia', 'UK']
现在,让我们看看如何通过调用dict
:
>>> dict(a=2, b=3)
{'a': 2, 'b': 3}
# or if we have a bunch of tuples, for example:
>>> items = [('a', 2), ('b', 3)]
>>> dict(items)
{'a': 2, 'b': 3}
# so it is evident, it takes key-value pairs, so:
# and we supply, keys = ['gender', 'car', 'country']
# if we have, rest = ['Male', 'kia', 'UK'], which are the values
# we can zip them together to get key value pairs:
>>> list(zip(keys, rest))
[('gender', 'Male'), ('car', 'kia'), ('country', 'UK')]
# now we can call dict
>>> dict(zip(keys, rest))
{'gender': 'Male', 'car': 'kia', 'country': 'UK'}
使用zip
和字典推导式:
dct = {n: {'gender': g, 'car': k, 'country': c}
for n, g, k, c in zip(name, gender, car, country)}
作为旁注,避免使用Python中的内置名称命名变量,例如dict
(我使用dct
代替,但更好的名称可能是people
,或者更好,您可以想到适合您实际用例的名称)。