Python - Dictionary Dictionary Creation


The following code shows different ways to create Dictionary objects.


D = {'name': 'Bob', 'age': 40}      # Traditional literal expression 
D = {}                              # Assign by keys dynamically 
D['name'] = 'Bob' 
D['age']  = 40 #   ww  w. ja v  a2  s.c o m
dict(name='Bob', age=40)            # dict keyword argument form 
dict([('name', 'Bob'), ('age', 40)])# dict key/value tuples form

The last form is commonly used in conjunction with the zip function to combine separate lists of keys and values obtained dynamically at runtime:

dict(zip(keyslist, valueslist))        # Zipped key/value tuples form (ahead) 

You can also create a dictionary by simply passing in a list of keys and an initial value for all of the values (the default is None):


print( dict.fromkeys(['a', 'b'], 0) )


Related Topics