-4

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

3 Answers3

0

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
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • That works perfectly until i print out the keys as well as the values, programs says, ValueError: too many values to unpack (expected 2) i used this because i want them to be on the same line: for key, vlaues in x_1: print(key,values) – Pratyush Khurana Dec 27 '14 at 16:20
  • @PratyushKhurana, `x_1.items()` returns both `key` and `value`, simple itertion over `x_1` returns only `key`. So use `for key, values in x_1: print(key,values)` instead. – Irshad Bhat Dec 27 '14 at 16:37
  • @PratyushKhurana: sounds like you want to iterate over `x_1.items()` instead then. – Martijn Pieters Dec 27 '14 at 16:58
  • 1
    @BHATIRSHAD: you actually forgot to include `.items()` in your sample. :-P – Martijn Pieters Dec 27 '14 at 17:03
  • It finally worked! :D Thank you so much for your quick responses guys! And sorry for taking up your time :p – Pratyush Khurana Dec 27 '14 at 17:10
0

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
Irshad Bhat
  • 8,479
  • 1
  • 26
  • 36
0

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!

Fomalhaut
  • 8,590
  • 8
  • 51
  • 95