for the list of tuples below:
x= [('a',1),('b', 2)]
I want to convert it to:
x_1 = {'a' : 1, 'b': 2}
if i use dict(x), the dict becomes unordered, i want it in the exact same order. really need this for my course work, please help fast
for the list of tuples below:
x= [('a',1),('b', 2)]
I want to convert it to:
x_1 = {'a' : 1, 'b': 2}
if i use dict(x), the dict becomes unordered, i want it in the exact same order. really need this for my course work, please help fast
Use collections.OrderedDict()
if order must be preserved:
>>> from collections import OrderedDict
>>> x= [('a',1),('b', 2)]
>>> x_1 = OrderedDict(x)
>>> for key in x_1:
... print(key)
...
a
b
You need collections.ordereddict
>>> from collections import OrderedDict
>>> x= [('a',1),('b', 2)]
>>> x = OrderedDict(x)
>>> x
OrderedDict([('a', 1), ('b', 2)]) # Order is preserved
This doesn't look like python dictionary but it actually is as can be seen from below examples:
>>> x['a']
1
>>> x['b']
2
>>> for key,val in x.items():
... print(key,val)
...
a 1
b 2
By definition, dictionary in Python (or associative array) is a disordered data structure, which stores key-value data and allows user has fast way to extract value by given key, to add a new pair key-value or remove an existing pair. This data structure must be disordered to make all necessary algorithms working quickly.
For more information about dictionary, see wikipedia.
If you do need to use order of keys, I would recommend you create dictionary and list or keys separately. It will take more memory, but will work faster, generally.
x = [('a', 1), ('b', 2)]
dct = dict(x) # dictionary
kys = zip(*x)[0] # tuple of keys
Good luck!