12

I trying to print out a dictionary in Python:

Dictionary = {"Forename":"Paul","Surname":"Dinh"}
for Key,Value in Dictionary.iteritems():
  print Key,"=",Value

Although the item "Forename" is listed first, but dictionaries in Python seem to be sorted by values, so the result is like this:

Surname = Dinh
Forename = Paul

How to print out these with the same order in code or the order when items are appended in (not sorted by values nor by keys)?

jondinham
  • 8,271
  • 17
  • 80
  • 137
  • 3
    You could use an additional list of keys to determine the order – Nobody moving away from SE Feb 29 '12 at 08:45
  • i'm thinking of using 2 lists (python arrays), then use "enumerate", but this is complex – jondinham Feb 29 '12 at 08:48
  • 3
    Do you also need the ability to access it quickly by key? – David Robinson Feb 29 '12 at 08:50
  • 4
    For dictionaries in Python, the order of elements is not guaranteed to be anything, so you can't assume that they are sorted by values. For example - `>>> Dictionary = {"Forename":"Paul","Surname":"Daih", "Middle": "Zarah"} >>> for Key,Value in Dictionary.iteritems(): ... print Key,"=",Value ... Middle = Zarah Surname = Daih Forename = Paul` – ronakg Feb 29 '12 at 08:53
  • @DavidRobinson yeah. accessing by key is important – jondinham Feb 29 '12 at 08:57
  • @RonakG but how come the result printed out is not like the order in code? what is the mechanism behind this iteritems()? mayby sorted by hash values? – jondinham Feb 29 '12 at 08:58
  • 4
    As I mentioned earlier, the order of the elements in a dictionary is not guaranteed to be anything specific. I'm not sure that is the mechanism behind iteritems(). – ronakg Feb 29 '12 at 09:06

7 Answers7

23

You can use a list of tuples (or list of lists). Like this:

Arr= [("Forename","Paul"),("Surname","Dinh")]
for Key,Value in Arr: 
    print Key,"=",Value

Forename = Paul
Surname = Dinh

you can make a dictionary out of this with:

Dictionary=dict(Arr)

And the correctly sorted keys like this:

keys = [k for k,v in Arr]

Then do this:

for k in keys: print k,Dictionary[k]

but I agree with the comments on your question: Would it not be easy to sort the keys in the required order when looping instead?

EDIT: (thank you Rik Poggi), OrderedDict does this for you:

od=collections.OrderedDict(Arr)
for k in od: print k,od[k]
Johan Lundberg
  • 26,184
  • 12
  • 71
  • 97
  • is it ok to use: Arr= [["Forename","Paul"],["Surname","Dinh"]] instead? – jondinham Feb 29 '12 at 08:51
  • 3
    list of tuples is how `OrderedDict`s are implemented, if dictionary is the structure the OP is looking for, the he should just use them and save the conversion pain every time. – Rik Poggi Feb 29 '12 at 09:25
17

First of all dictionaries are not sorted at all nor by key, nor by value.

And basing on your description. You actualy need collections.OrderedDict module

from collections import OrderedDict

my_dict = OrderedDict([("Forename", "Paul"), ("Surname", "Dinh")])

for key, value in my_dict.iteritems():
    print '%s = %s' % (key, value)

Note that you need to instantiate OrderedDict from list of tuples not from another dict as dict instance will shuffle the order of items before OrderedDict will be instantiated.

lig
  • 3,567
  • 1
  • 24
  • 36
6

You can use collections.OrderedDict. It's available in python2.7 and python3.2+.

strcat
  • 5,376
  • 1
  • 27
  • 31
5

This may meet your need better:

Dictionary = {"Forename":"Paul","Surname":"Dinh"}
KeyList = ["Forename", "Surname"]
for Key in KeyList:
    print Key,"=",Dictionary[Key]
Felix Yan
  • 14,841
  • 7
  • 48
  • 61
3

'but dictionaries in Python are sorted by values' maybe I'm mistaken here but what game you that ideea? Dictionaries are not sorted by anything.

You would have two solutions, either keep a list of keys additional to the dictionary, or use a different data structure like an array or arrays.

Bogdan
  • 8,017
  • 6
  • 48
  • 64
3

I wonder if it is an ordered dict that you want:

>>> k = "one two three four five".strip().split()
>>> v = "a b c d e".strip().split()
>>> k
  ['one', 'two', 'three', 'four', 'five']
>>> v
  ['a', 'b', 'c', 'd', 'e']
>>> dx = dict(zip(k, v))
>>> dx
   {'four': 'd', 'three': 'c', 'five': 'e', 'two': 'b', 'one': 'a'}
>>> for itm in dx: 
        print(itm)

   four
   three
   five
   two
   one

>>> # instantiate this data structure from OrderedDict class in the Collections module
>>> from Collections import OrderedDict
>>> dx = OrderedDict(zip(k, v))
>>> for itm in dx:
        print(itm)

   one
   two
   three
   four
   five 

A dictionary created using the OrderdDict preserves the original insertion order.

Put another way, such a dictionary iterates over the key/value pairs according to the order in which they were inserted.

So for instance, when you delete a key and then add the same key again, the iteration order is changes:

>>> del dx['two']
>>> for itm in dx:
        print(itm)

       one
       three
       four
       five

>>> dx['two'] = 'b'
>>> for itm in dx:
        print(itm)

       one
       three
       four
       five
       two
doug
  • 69,080
  • 24
  • 165
  • 199
  • is that necessary in order for you to understand my answer? In fact, i did not use the OP's sample data for two reasons: (i) we are talking about ordered sequences here and the OP's data only has *two* keys-value pairs; and (ii) i chose keys and values for my sample data that allow a reader to easily see the point of my code--i.e., order preservation. – doug Feb 29 '12 at 09:07
0

As of Python 3.7, regular dicts are guaranteed to be ordered, so you can just do

Dictionary = {"Forename":"Paul","Surname":"Dinh"}
for Key,Value in Dictionary.items():
  print(Key,"=",Value)