A dictionary is an example of a key-value store also known as Mapping in Python. It allows you to store and retrieve elements by referencing a key. As dictionaries are referenced by key, they have very fast lookups. As they are primarily used for referencing items by key, they are not sorted.
Dictionaries can be initiated in many ways:
d = {} # empty dict
d = {'key': 'value'} # dict with initial values
d = dict() # empty dict
d = dict(key='value') # explicit keyword arguments
d = dict([('key', 'value')])
Rules for creating a dictionary:
# 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)
mydict['b'].append('four')
# We can also create a dictionary using a list of two-items tuples
iterable = [('eggs', 5), ('milk', 2)]
dictionary = dict(iterables)
# Or using keyword argument:
dictionary = dict(eggs=5, milk=2)
#by aman kharwal #python #data science