What would be a nice way to go from {2:3, 1:89, 4:5, 3:0} to {1:89, 2:3, 3:0, 4:5}?
I checked some posts but they all use the "sorted" operator that returns tuples.
Dec 28, 2020 in Python 515 views

## 3 answers to this question.

Standard Python dictionaries are unordered. Even if you sorted the (key,value) pairs, you wouldn't be able to store them in a dict in a way that would preserve the ordering.

The easiest way is to use OrderedDict, which remembers the order in which the elements have been inserted:

```In : import collections

In : d = {2:3, 1:89, 4:5, 3:0}

In : od = collections.OrderedDict(sorted(d.items()))

In : od
Out: OrderedDict([(1, 89), (2, 3), (3, 0), (4, 5)])
```

Never mind the way od is printed out; it'll work as expected:

```In : od
Out: 89

In : od
Out: 0

In : for k, v in od.iteritems(): print k, v
....:
1 89
2 3
3 0
4 5
```

Python 3

For Python 3 users, one needs to use the .items() instead of .iteritems():

```In : for k, v in od.items(): print(k, v)
....:
1 89
2 3
3 0
4 5```
• 65,910 points
Load the Dictionary and perform the following operations:

First, sort the keys alphabetically using key_value.iterkeys() function.
Second, sort the keys alphabetically using sorted (key_value) function & print the value corresponding to it.
Third, sort the values alphabetically using key_value.iteritems(), key = lambda (k, v) : (v, k))

Displaying the Keys Alphabetically:
Examples:

Input:
key_value = '64'
key_value = '69'
key_value = '23'
key_value = '65'
key_value = '34'
key_value = '76'

Output:
1 2 3 4 5 6
Program:

# Function calling
def dictionairy():
# Declare hash function
key_value ={}

# Initializing value
key_value = 56
key_value = 2
key_value = 12
key_value = 24
key_value = 18
key_value = 323

print ("Keys are")

# iterkeys() returns an iterator over the
# dictionary’s keys.
for i in sorted (key_value.keys()) :
print(i, end = " ")

def main():
# function calling
dictionairy()

# Main function calling
if __name__=="__main__":
main()
Output:

Keys are
1 2 3 4 5 6
answered Dec 28, 2020 by Carlos
Another way could be:
color_dict = {'red':'#FF0000',
'green':'#008000',
'black':'#000000',
'white':'#FFFFFF'}

for key in sorted(color_dict):
print("%s: %s" % (key, color_dict[key]))

Sample Output:

black: #000000
green: #008000
red: #FF0000
white: #FFFFFF
answered Dec 28, 2020 by Thomas Walenta

## How can I rename a file in Python?

yes, you can use "os.rename" for that. ...READ MORE

## How can I create a new file in Python?

You can try the below code which ...READ MORE

## In a list of dictionaries, how can I find the minimum calue in a common dictionary field.

There are several options. Here is a ...READ MORE

## how can i randomly select items from a list?

You can also use the random library's ...READ MORE

+1 vote

## how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

## Lowercase in Python

You can simply the built-in function in ...READ MORE