dict() constructor builds dictionaries directly from lists of key-value pairs : Dictionary Declaration « Dictionary « Python






dict() constructor builds dictionaries directly from lists of key-value pairs

# dict() constructor builds dictionaries directly from lists of key-value pairs stored 
# as tuples. 


print dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])

print dict([(x, x**2) for x in (2, 4, 6)])     # use a list comprehension


# When the keys are simple strings, it is sometimes easier to specify pairs using 
# keyword arguments:

print dict(sape=4139, guido=4127, jack=4098)



           
       








Related examples in the same category

1.Dictionaries are indexed by keys, which can be any immutable type
2.Defining Dictionaries: shows an example of a dictionary definition.