Python Dictionaries: Instantiation

Creating an empty dictionaries in Python:

1)myDictioanry = dict()

OR

2)myDictionary = {}

Creating a populated dictionaries in Python:

1)myDictionary = dict(key1 = 'value1', key2 = 'value2')

OR

2)myDictionary = {'key1' : 'value1', 'key2' : 'value2'}

Method 1 Notes:

The keys will be strings in our instantiated dictionary, but notice that they are not quoted. If you try to use quotes you get an error:

SyntaxError: keyword can't be an expression

This also means you cannot make keys variables, it will always treat the keyword as a string:

key1 = 'MyKey'
myDictionary = dict(key1 = 'value1', key2 = 'value2')
print myDictionary

Output:
{'key2': 'value2', 'key1': 'value1'}

You can, however, use variables (and thus any object) for your values:

value1 = 'myValue'
value2 = ['python', 'is', 'pretty', 'cool']
myDictionary = dict(key1 = value1, key2 = value2)
print myDictionary

Output:
{'key2': ['python', 'is', 'pretty', 'cool'], 'key1': 'myValue'}

Method 2 Notes:

Here we quote the keyword to indicate it is a string. Using {} to instantiate the dictionary allows us to use variables in the keys as well as variables, so it seems to be the more powerful of the two methods

key2 = 'MyKey'
value1 = 'MyValue'
value2 = ['python', 'is', 'pretty', 'cool']
myDictionary = { 'key1' : value1, key2 : value2 }
print myDictioanry

Output:
{'key1': 'MyValue', 'MyKey': ['python', 'is', 'pretty', 'cool']}

Leave a Reply

Your email address will not be published. Required fields are marked *

*