Home > Software engineering >  From a list create a dictionary with Keys equal to values
From a list create a dictionary with Keys equal to values

Time:10-06

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:

{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.

CodePudding user response:

You can try this:

dicts[values[i]] = values[i]

CodePudding user response:

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

and don't forget to define x first : x = ['a','b','c']

this will output :

{'a': 'a', 'b': 'b', 'c': 'c'}

CodePudding user response:

You can use dict comprehension

values = ['a','b','c']
d = {v:v for v in values}

CodePudding user response:

IIUC, you have values = ['a','b','c'] you can create dict with zip like below:

values = ['a','b','c']
dict(zip(values, values))

Output:

{'a': 'a', 'b': 'b', 'c': 'c'}

CodePudding user response:

Try:

dict(zip(values, values))

CodePudding user response:

You can use the dict function on zipping the list twice:

x = ['a', 'b', 'c']
dict(zip(*[x]*2))

{'a': 'a', 'b': 'b', 'c': 'c'}
  • Related