0

I have list:

my_list=[['a',1], ['b', 2]]

I want my_dict['a']=1 and my_dict['b']=2

Is there easy way, without looping?

user3654650
  • 5,283
  • 10
  • 27
  • 28

2 Answers2

4

There is, like this:

>>> my_list=[['a',1], ['b', 2]]
>>> my_dict = dict(my_list)
>>> my_dict
{'a': 1, 'b': 2}

Basically your list is already compatible with the dict constructor. (i.e: A list of 2-item tuples/lists or more precisely an iterable that yields 2-item lists/tuples -- key/value pairs).

James Mills
  • 18,669
  • 3
  • 49
  • 62
  • although Im pretty sure somewhere under the hood this is looping also ... but yeah +1 to both you guys – Joran Beasley May 20 '14 at 00:36
  • It's all hidden away in CPython's implemtnation somewhere :) At least ``dict`` is a builtin type :) AFAIK tehre is no user code except for ``UserDict`` which I'm pretty sure just subclasses ``dict``. There's also ``collections.Mapping`` – James Mills May 20 '14 at 00:37
2

Use dict:

In [138]: my_list=[['a',1], ['b', 2]]

In [139]: my_dict = dict(my_list)

In [140]: my_dict
Out[140]: {'a': 1, 'b': 2}
Marcin
  • 215,873
  • 14
  • 235
  • 294