Creating a dictionary
suggest changeRules for creating a dictionary:
- Every key must be unique (otherwise it will be overridden)
- Every key must be hashable (can use the
hashfunction to hash it; otherwiseTypeErrorwill be thrown) - Since Python 3.7, keys keep insertion order. They are not kept sorted.
# Creating and populating it with values
stock = {'eggs': 5, 'milk': 2}
# Or creating an empty dictionary
dictionary = {}
# And populating it after
dictionary['eggs'] = 5
dictionary['milk'] = 2
# Values can also be lists
mydict = {'a': [1, 2, 3], 'b': ['one', 'two', 'three']}
# Use list.append() method to add new elements to the values list
mydict['a'].append(4) # => {'a': [1, 2, 3, 4], 'b': ['one', 'two', 'three']}
mydict['b'].append('four') # => {'a': [1, 2, 3, 4], 'b': ['one', 'two', 'three', 'four']}
# We can also create a dictionary using a list of two-item tuples
iterable = [('eggs', 5), ('milk', 2)]
dictionary = dict(iterable)
# Or using keyword arguments:
dictionary = dict(eggs=5, milk=2)
# Another way is to use dict.fromkeys. The second argument is one shared value, not a per-key sequence:
dictionary = dict.fromkeys(('milk', 'eggs')) # => {'milk': None, 'eggs': None}
dictionary = dict.fromkeys(('milk', 'eggs'), (2, 5)) # => {'milk': (2, 5), 'eggs': (2, 5)}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents