简体   繁体   English

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

[英]how join list tuple and dict into a dict?

how join list tuple and dict into a 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'}

You can make a dict from keys and values like so: 你可以用键和值来制作一个dict

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

Then you can update it with another dict 然后你可以用另一个词典来更新它

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

when a_list is your list, a_tuple is your tuple and a_dictionary is your dictionary. 当a_list是你的列表时,a_tuple是你的元组,a_dictionary是你的字典。

EDIT: If you really wanted to turn the numbers in you tuple into strings than first do: 编辑:如果你真的想把你的元组中的数字变成字符串,而不是先做:

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

and pass new_tuple to the zip function. 并将new_tuple传递给zip函数。

This will accomplish the first part of your question: 这将完成您问题的第一部分:

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

However, the second part of your question would require a second definition of 'a', which the dictionary type does not allow. 但是,问题的第二部分需要第二个定义'a',字典类型不允许。 However, you can always set additional keys manually: 但是,您始终可以手动设置其他键:

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

The keys in a dictionary must be unique, so this part: {'a':'1','a':'10'} is impossible. 字典中的键必须是唯一的,所以这部分: {'a':'1','a':'10'}是不可能的。

Here is code for the rest: 以下是其余的代码:

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

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

Something like this? 像这样的东西?

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

Since noone has given an answer that converts the tuple items to str yet 由于没有人给出了将元组项转换为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'}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM