Dictionaries in Python
We have seen, list/sequences in the previous article. In this article, we will learn about Dictionaries in Python. If you are familiar with other languages then you can think of dictionaries as Map or hash tables. The python dictionary is an unordered collection of items having
We will see:
- How to create a Dictionary?
- How to access the Dictionary element?
- How to modify a Dictionary?
- Dictionary Methods
- Dictionary Built-in Functions
How to create a Dictionary?
We can create a dictionary by simply putting elements in {} separated by commas. Elements will have
Below is some of the way of creating a dictionary:
# creating empty dictionary demo_dict = {} # creating dictionary with integer keys demo_dict = {1: 'code', 2: 'pumpkin'} # creating dictionary with mixed keys demo_dict = {'name': 'Dipen', 1: [1, 2, 4, 3]} # using dict() built-in dict constroctor demo_dict = dict( {1: 'code', 2: 'pumpkin'}) # from sequence/list having each item as a pair demo_dict = dict([(1,'code'), (2,'pumpkin')])
How to access the Dictionary element?
Elements of a dictionary cannot be accessed using indexes. To access an element of a dictionary one can use key inside square brackets or using the get() methods.
The difference while using get() is that it returns None instead of KeyError if the key is not found.
demo_dict = {'name':'Pumpkin', 'experience': 27} # Output: Pumpkin print(demo_dict['name']) # Output: 27 print(demo_dict.get('experience')) # this will return null print('This is my value',demo_dict.get('address')) # Trying to access keys which doesn't exist throws error demo_dict['address']
Output:
Pumpkin
27
('This is my value', None)
Traceback (most recent call last):
File "demo.py", line 11, in <module>
demo_dict[‘address’]
KeyError: 'address'
How to modify a Dictionary?
Dictionaries are mutable objects. We can add new elements and or change the value of the existing element. If the
demo_dict = {'name':'Pumpkin', 'experience': 27, 'category': 'vip'} # Update value demo_dict['name'] = "CodePumpkin" print(demo_dict) demo_dict['age'] = 40 print(demo_dict) # remove particular element from dict print(demo_dict.pop('experience')) # delete a particular element del demo_dict['category'] print(demo_dict) # remove all elements from dicts demo_dict.clear() print(demo_dict)
Output:
{'category': 'vip', 'name': 'CodePumpkin', 'experience': 27}
{'category': 'vip', 'age': 40, 'name': 'CodePumpkin', 'experience': 27}
27
{'age': 40, 'name': 'CodePumpkin'}
{}
Dictionary Methods
Below is the list of the methods available for the dictionary.
Method | Description |
---|---|
clear() | Remove all elements from the dictionary. |
copy() | Return a shallow copy of the dictionary. |
| Return a new dictionary with keys from seq and value equal to v(defaults to None). |
get(key[,d]) | Return the value of key. If the key doesn't exist, return d (defaults to None). |
items() | Return a new view of the dictionary's items (key, value). |
keys() | Return a new view of the dictionary's keys. |
pop(key[,d]) | Remove the item with the key and return its value or d if the key is not found. If d is not provided and the key is not found, raises KeyError |
popitem() | Remove and return an arbitary item (key, value). Raises KeyError if the dictionary is empty. |
setdefault(key[,d]) | If key is in the dictionary, return its value. If not, insert key with a value of d and return d (defaults to None). |
update([other]) | Update the dictionary with the key/value pairs from other, overwriting existing keys. |
values() | Return a new view of the dictionary's values |
Dictionary Built-in Functions
Below is
Function | Description |
---|---|
all() | Return True if all keys of the dictionary are true (or if the dictionary is empty). |
any() | Return True if any key of the dictionary is true. If the dictionary is empty, return False. |
len() | Return the length (the number of items) in the dictionary. |
| Compares items of two dictionaries. |
sorted() | Return a new sorted list of keys in the dictionary. |
Dictionary Comprehension
We can create a new dictionary from the iterable in Python. The syntax for the same is as below:
demo_dict = {i : i * 2 for i in range(10)}
Comprehension is one of the elegant ways of creating the dictionary. Along with for loop we can also add if statement to filter from iterable elements.
That's all for this topic. If you guys have any suggestions or queries, feel free to drop a comment. We would be happy to add that in our post. You can also contribute your articles by creating contributor account here.
Happy Learning 🙂
If you like the content on CodePumpkin and if you wish to do something for the community and the planet Earth, you can donate to our campaign for planting more trees at CodePumpkin Cauvery Calling Campaign.
We may not get time to plant a tree, but we can definitely donate ₹42 per Tree.
About the Author
Tags: python
Comments and Queries
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:<pre><code class="java"> String foo = "bar"; </code></pre>For more information on supported HTML tags in disqus comment, click here.