Building a dictonnary using comprehension

An easy way to create a dictionnary in python is to use the comprehension syntaxe. It can be more expressive hence easier to read.

d = {key: value for (key, value) in iterable}

In the example bellow we use the dictionnary comprehension to build a dictonnary from a source list.

iterable = list(range(10))
d = {str(value): value**2 for value in iterable} # create a dictionnary linking the string value of a number with the square value of this number
print(d)
{'0': 0, '1': 1, '2': 4, '3': 9, '4': 16, '5': 25, '6': 36, '7': 49, '8': 64, '9': 81}

of course, you can use an other iterable an repack it with the comprehension syntaxe. In the following example, we convert a list of tuples in a dictonnary.

iterable = [("France",67.12e6), ("UK",66.02e6), ("USA",325.7e6), ("China",1386e6), ("Germany",82.79e6)]
population = {key: value for (key, value) in iterable}
print(population)
{'France': 67120000.0, 'UK': 66020000.0, 'USA': 325700000.0, 'China': 1386000000.0, 'Germany': 82790000.0}