Python - Dictionary Dictionary Creation

Introduction

The following code shows different ways to create Dictionary objects.

Demo

D = {'name': 'Bob', 'age': 40}      # Traditional literal expression 
D = {}                              # Assign by keys dynamically 
D['name'] = 'Bob' 
D['age']  = 40 # from  ww  w. ja  va2s .  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):

Demo

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

Result

Related Topics