How to Compile a Dictionary of Numbers in Python

Python dictionaries are sets of key-value pairs. Each key has one or more attached values. For example: 'favoritecolor' : 'green', 'favoritefood' : 'chinese'. Here, 'favoritecolor' and 'favoritefood' are keys with the corresponding value of 'green' and 'chinese', respectively. You can create a dictionary of numbers in Python, whether the key-value pairs are duplicates as in '1' : '1', if the pairs include both words and numbers as in '1' : 'one' or if the pairs include foreign words such as 'one' : 'uno'. You can create such a dictionary manually or, in some circumstances, with a loop.

Instructions

1

Type the following to create your dictionary manually in a single command:

mynumbers = { '1' : 'one', '2' : 'two', '3' : 'three', '4' : 'four' }

2

Type the following to create a blank dictionary and add numbers to it individually:

mynumbers = {}
mynumbers['1'] = 'one'
mynumbers['2'] = 'two'
mynumbers['3'] = 'three'

This would result in the following dictionary: { '1' : 'one', '2' : 'two', '3' : 'three' }

3

Use a loop to generate a dictionary of numbers if both keys and values will be integers, and in numeric order:

mynumbers = {}
x = 1
while (x < 4):
mynumbers[x] = x
x = x + 1

This code results in the dictionary: { 1 : 1, 2 : 2, 3 : 3 }

Tips & Warnings

  • While key-value pairs always stay together, a Python dictionary is not ordered. This means that each time you read it the items within the dictionary may come back in a different order. Do not count on your dictionary being in numerical order.