在固定位置向词典添加列表元素

2024-04-29 22:26:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有如下清单:

   List = ['blue', 'Ford', 'Mustang']

我要获取这些值并将它们插入到已具有以下值的词典中:

 dictionary = {'Color': ' ', 'Make': ' ', Model: ' '}

我的结果是

 dictionary = {'Color': 'blue', 'Make': 'Ford', Model: 'Mustang'}

我在用Python3。你知道吗


Tags: makemodeldictionarybluepython3list词典color
3条回答

在我的代码中,首先我将字典转换为一个列表,并将两个列表聚合在一起以获得所需的输出。这是我的密码:

list_1 = ['blue', 'Ford', 'Mustang']
dictionary = {'Color': ' ', 'Make': ' ', 'Model': ' '}.keys()
converter = dict(zip(dictionary, list_1))
print(converter)

您必须精确地指定列表中的哪个值与字典中的哪个键匹配。你也应该这样做:

l = ['blue', 'Ford', 'Mustang']
d = {'Color': ' ', 'Make': ' ', 'Model': ' '}

print "Before inserting:",d

d['Color']=l[0]
d['Make']=l[1]
d['Model']=l[2]

print "After inserting:",d

除非您使用的是python3.7+,否则字典被认为是无序的。你知道吗

因此,您要么显式地为键赋值,要么使用OrderedDict。你知道吗

订购信息

注意我们必须如何使用元组列表定义OrderedDict。你知道吗

from collections import OrderedDict

L = ['blue', 'Ford', 'Mustang']
d = OrderedDict([('Color', ' '), ('Make', ' '), ('Model', ' ')])

res = dict(zip(d, L))

print(res)
{'Color': 'blue', 'Make': 'Ford', 'Model': 'Mustang'}

显式赋值

在这里,我们只是从两个列表组成一个字典。你知道吗

L = ['blue', 'Ford', 'Mustang']
K = ['Color', 'Make', 'Model']

res = dict(zip(K, L))

请注意,与通过dict(zip(..., ...))生成新词典相比,更新现有词典没有显著的性能优势。这两个过程都具有O(n)复杂性。你知道吗

相关问题 更多 >