怎么加入列表元组和字典成为一个字典?

时间:2010-08-16 20:52:16

标签: python

如何将列表元组和dict连接成dict?

['f','b','c','d'] (1,2,3) and {'a':'10'}
d excluded for list be compatible with the tuple

output {'f':'1','b':'2','c':'3','a':'10'}

7 个答案:

答案 0 :(得分:8)

您可以从键和值中创建dict,如下所示:

keys = ['a','b','c','d']
values = (1,2,3)
result = dict(zip(keys, values)) # {'a': 1, 'c': 3, 'b': 2}

然后你可以用另一个词典更新它

result.update({ 'f' : 5 })
print result # {'a': 1, 'c': 3, 'b': 2, 'f': 5}

答案 1 :(得分:3)

dict(zip(a_list, a_tuple)).update(a_dictionary)

当a_list是你的列表时,a_tuple是你的元组,a_dictionary是你的字典。

修改 如果你真的想把你的元组中的数字变成字符串而不是第一次:

new_tuple = tuple((str(i) for i in a_tuple))

并将new_tuple传递给zip函数。

答案 2 :(得分:1)

这将完成你问题的第一部分:

dict(zip(['a','b','c','d'], (1,2,3)))

但是,问题的第二部分需要第二个定义'a',字典类型不允许。但是,您始终可以手动设置其他密钥:

>>> d = {}
>>> d['e'] = 10
>>> d
{'e':10}

答案 3 :(得分:0)

字典中的键必须是唯一的,因此这部分:{'a':'1','a':'10'}是不可能的。

以下是其余的代码:

l = ['a','b','c','d']
t = (1,2,3)

d = {}
for key, value in zip(l, t):
    d[key] = value

答案 4 :(得分:0)

这样的东西?

>>> dict({'a':'10'}.items() + (zip(['f','b','c','d'],('1','2','3'))))
{'a': '10', 'c': '3', 'b': '2', 'f': '1'}

答案 5 :(得分:0)

由于没有人给出将元组项转换为str的答案

>>> L=['f','b','c','d']
>>> T=(1,2,3)
>>> D={'a':'10'}
>>> dict(zip(L,map(str,T)),**D)
{'a': '10', 'c': '3', 'b': '2', 'f': '1'}

答案 6 :(得分:0)

>>> l = ['a','b','c','d']
>>> t = (1,2,3)
>>> d = {'a':'10'}
>>> t = map(str, t)  # the OP has requested str values, let's do this first

如果您可以改变原始字典,那么您可以这样做:

>>> d.update(zip(l, t))

或在 Python 3.9+ (PEP 584) 中:

>>> d |= zip(l, t)

但如果您需要保持原来的 d 不变:

>>> new_d = dict(zip(l, t))
>>> new_d |= d