1. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Nov 2012
Posts
2
Rep Power
0

#### Ordering a diccionary

Hey guys, I'm new here so hi to everyone! Just got your self's another python newb :/ sorry..

Anyways, any help with the following will be much appreciated!

I got this code:

en_es = {'one':'uno',
'two':'dos',
'three':'tres',
'four':'quatro',
'five':'cinco}'

def write_diccionary(d):
temp = []
k = d.keys()
k = list(k)
temp = k[1]
k[1] = k[4]
k[4] = temp
for i in k:
print(i,':',d[i])

The idea is to take the dictionary above, and order it. The code is fixed for a single situation where I know the positions of the (key,value) pairs. However I would like generalize this. I made this attempt:

def write_diccionary_2(d):
for k in sorted(d): print(k,':', d[k])

however the output is:

>>> write_diccionary_2(en_es)

five : cinco
two : dos
four : cuatro
three : tres
one : uno

Can someone please shed some light on this?

THANKS!
2. Your program works on my system. The python prompts are cluttered because I entered data in multi-line chunks.
Code:
```\$ python3
Python 3.2.3 (default, Oct 19 2012, 19:53:16)
[GCC 4.7.2] on linux2
>>> en_es = {'one':'uno',
'two':'dos',
'three':'tres',
'four':'quatro',
'five':'cinco'}

... ... ... ... >>> >>> >>> def write_diccionary_2(d):
for k in sorted(d): print(k,':', d[k])
... ...
>>> write_diccionary_2(en_es)
five : cinco
four : quatro
one : uno
three : tres
two : dos
>>>```
You are aware of the typographical error in your post?

'five':'cinco}'
3. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Nov 2012
Posts
2
Rep Power
0
Originally Posted by b49P23TIvg
Your program works on my system. The python prompts are cluttered because I entered data in multi-line chunks.
Code:
```\$ python3
Python 3.2.3 (default, Oct 19 2012, 19:53:16)
[GCC 4.7.2] on linux2
>>> en_es = {'one':'uno',
'two':'dos',
'three':'tres',
'four':'quatro',
'five':'cinco'}

... ... ... ... >>> >>> >>> def write_diccionary_2(d):
for k in sorted(d): print(k,':', d[k])
... ...
>>> write_diccionary_2(en_es)
five : cinco
four : quatro
one : uno
three : tres
two : dos
>>>```
You are aware of the typographical error in your post?

'five':'cinco}'

that last typo was a copy error, it's ok in my code, but thanks.

About this last code, the problem is that I want the output to be (which I can achieve with the first code):

one : uno
two : dos
three : tres
four : quatro
five : cinco

Instead of what python is giving me...

sorry, should have mentioned it before..
4. My answer was ridiculous. Sorry. You need an ordered dictionary.
Code:
```>>> import collections
>>> d = collections.OrderedDict()
>>> d['one']='eins'
>>> d['two']='zwei'
>>> d['three']='drei'
>>> d['four']='vier'
>>> import pprint
>>> pprint.pprint(d)
{'one': 'eins',
'two': 'zwei',
'three': 'drei',
'four': 'vier'}```
(pprint didn't impact the dictionary order)