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.

Creating a Dictionary

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:

  • Every key must be unique (otherwise it will be overridden)
  • Every key must be hashable (can use the hash function to hash it; otherwise TypeError will be thrown)
  • There is no particular order for the keys.
# 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

Dictionary in Python | Data Science | Machine Learning | Python
9.65 GEEK