WHAT IS A DICTIONARY IN PYTHON


Dictionaries

A dictionary is a mapping of keys to values. It’s also sometimes called a hash table or associative array. The keys serve as indices for accessing values. Dictionaries are written with curly brackets as shown in the below examples.

Dictionaries in python are used to store data values in key: value pairs each pair is separated by a comma and all pairs are enclosed in curly brackets.

A dictionary in python is a collection that is ordered, changeable, and does not allow duplicates.

Dictionaries in python are ordered, which means that the items have a defined order, and that order will not change.

Dictionaries in python are changeable, meaning that we can change, add or remove items after the dictionary has been created.

Dictionaries in python don’t allow duplicates, meaning that we cannot have two items with the same key.

s = {
'name': 'GOOG',
'shares': 100,
'price': 490.1
}
Common operations
How to Access values from a dictionary?

Use the key names.

>>> print(s['name'], s['shares'])
GOOG 100
>>> s['price']
490.10
>>>

Use the get() method.

>>> x=s.get('name')

Use the keys() function to get the list of all keys in the dictionary.

>>> x=s.keys()
How to Access items from a dictionary?

Use the items() function.

It will return each item in a dictionary, as tuples in a list.

>>> x=s.items()
How to add or modify values IN DICTIONARY?

Assign values using the key names.

>>> s['shares'] = 75
>>> s['date'] = '6/6/2007'
>>>

Use update() function

The update() function will update the dictionary with the items from the given argument. The argument must be a dictionary, or an iterable object with key:value pairs.

s = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
s.update({"year": 2020})
How to delete a value IN DICTIONARY?

Use the del statement.

>>> del s['date']
>>>
How to determine the length of DICTIONARY?

Use the len function

>>> print(len(s))
>>>
What is the data type of items in the dictionary?

The values in dictionary items can be of any data type.

Dictionaries are defined as objects with the data type ‘dict’.

Use the type function to identify the data type of the dictionary object.

Example

>>> print(type(s))
How to make dictionary object using a constructor?

Use the dict() function as Constructor –

>>> a = dict(name = "Jonny", age = 38, country = "India")
>>> print(a)
How To check if a specified key is present in a dictionary?

Use the in keyword-

s = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in s:
print("Yes, 'model' is one of the keys in the s dictionary")

Why dictionaries?
Dictionaries are useful when there are many different values and those values might be modified or manipulated. Dictionaries make your code more readable.

s['price']
# vs
s[2]

Leave a Reply

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