Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make dictionary from list with python [duplicate]

People also ask

Can dictionary have duplicate values Python?

The straight answer is NO. You can not have duplicate keys in a dictionary in Python.

Can dictionary have duplicate items?

The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.

Can you have duplicate values in a list Python?

A Python list can also contain duplicates, and it can also contain multiple elements of different data types. This way, you can store integers, floating point numbers, positive or negatives, strings, and even boolean values in a list.


dict(x[i:i+2] for i in range(0, len(x), 2))

Here are a couple of ways for Python3 using dict comprehensions

>>> x = (1,'a',2,'b',3,'c')
>>> {k:v for k,v in zip(*[iter(x)]*2)}
{1: 'a', 2: 'b', 3: 'c'}
>>> {x[i]:x[i+1] for i in range(0,len(x),2)}
{1: 'a', 2: 'b', 3: 'c'}

dict(zip(*[iter(val_)] * 2))

>>> x=(1,'a',2,'b',3,'c')
>>> dict(zip(x[::2],x[1::2]))
{1: 'a', 2: 'b', 3: 'c'}

x = (1,'a',2,'b',3,'c') 
d = dict(x[n:n+2] for n in xrange(0, len(x), 2))
print d