[英]From a list create a dictionary with Keys equal to values
my pourpose is to create a dictionary starting from a list, where the keys are equal to the values.我的目的是从一个列表开始创建一个字典,其中键等于值。 What I have done till now is:到目前为止我所做的是:
dicts = {}
keys = range(len(x))
values = x
for i in keys:
dicts[i] = values[i]
the output is: output 是:
{0: 'a', 1: 'b', 2: 'c'}
what I want is:我想要的是:
{a: 'a', b: 'b', c: 'c'}
I don't know how modify the keys.我不知道如何修改密钥。 Thanks you all.谢谢大家。
You can try this:你可以试试这个:
dicts[values[i]] = values[i]
Try:尝试:
dict(zip(values, values))
The problem is in your last line Your saying: dicts[i] = values[i]
instead put: dicts[values[i]] = values[i]
Cause i
is the index not the item in the list问题出在你的最后一行 你说: dicts[i] = values[i]
而不是: dicts[values[i]] = values[i]
因为i
是索引而不是列表中的项目
and don't forget to define x first: x = ['a','b','c']
不要忘记先定义 x: x = ['a','b','c']
this will output:这将是 output:
{'a': 'a', 'b': 'b', 'c': 'c'} {'a': 'a', 'b': 'b', 'c': 'c'}
You can use dict comprehension您可以使用字典理解
values = ['a','b','c']
d = {v:v for v in values}
You can use the dict
function on zipping the list twice:您可以使用dict
function 将列表压缩两次:
x = ['a', 'b', 'c']
dict(zip(*[x]*2))
{'a': 'a', 'b': 'b', 'c': 'c'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.