Dictionaries in Python
A Python dictionary is a data structure that stores the value in key: value pairs. Values in a dictionary can be of any data type and can be duplicated, whereas keys can’t be repeated and must be immutable.
Example: Here, The data is stored in key: value pairs in dictionaries, which makes it easier to find values.
d = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print(d)
Create a Dictionary
In Python, a dictionary can be created by
placing a sequence of elements within curly {} braces, separated by a ‘comma’.
# create dictionary using { }
d1 = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print(d1)
# create dictionary using dict() constructor
d2 = dict(a = "Geeks", b =
"for", c = "Geeks")
print(d2)
- From Python 3.7 Version onward, Python dictionary are Ordered.
- Dictionary keys are case sensitive: the same name but different cases of Key will be treated distinctly.
- Keys must be immutable: This means keys can be strings, numbers, or tuples but not lists.
- Keys must be unique: Duplicate keys are not allowed and any duplicate key will overwrite the previous value.
- Dictionary internally uses Hashing. Hence, operations like search, insert, delete can be performed in Constant Time.
- Print the data type of a dictionary:
thisdict = {"brand": "Ford","model": "Mustang","year": 1964}
print(type(thisdict))
- The dict() Constructor
It is also possible to use the dict() constructor to make a dictionary.
Example
Using the dict() method to make a dictionary:
thisdict = dict(name = "John", age = 36, country = "Norway")
print(thisdict)
- Accessing Dictionary Items
We can
access a value from a dictionary by using the key within
square brackets or get()method.
d = {
"name": "Alice", 1: "Python", (1, 2): [1,2,4] }
# Access
using key
print(d["name"])
# Access
using get()
print(d.get("name"))
- Adding
and Updating Dictionary Items
We can add
new key-value pairs or update existing keys by using assignment.
d = {1:
'Geeks', 2: 'For', 3: 'Geeks'}
# Adding a
new key-value pair
d["age"]
= 22
# Updating
an existing value
d[1] =
"Python dict"
print(d)
- Removing
Dictionary Items
We can
remove items from dictionary using the following methods:
·
del: Removes an item by key.
·
pop(): Removes an item by key and returns its value.
·
clear():
Empties the dictionary.
·
popitem(): Removes and returns the last key-value pair.
d = {1:
'Geeks', 2: 'For', 3: 'Geeks', 'age':22}
# Using del
to remove an item
del
d["age"]
print(d)
# Using
pop() to remove an item and return the value
val =
d.pop(1)
print(val)
# Using
popitem to removes and returns
# the last
key-value pair.
key, val =
d.popitem()
print(f"Key:
{key}, Value: {val}")
# Clear all
items from the dictionary
d.clear()
print(d)
- Iterating
Through a Dictionary
We can
iterate over keys [using keys() method] , values [using values()
method] or both [using item() method] with a for loop.
d = {1: 'Geeks', 2: 'For', 'age':22}
# Iterate
over keys
for key in
d:
print(key)
# Iterate
over values
for value
in d.values():
print(value)
# Iterate
over key-value pairs
for key,
value in d.items():
print(f"{key}: {value}")
- Nested Dictionaries
Example of nested Dictionaries
d = {1: 'Geeks', 2: 'For',
3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}}
print(d)
Python Dictionary Problems
- Length of a Dictionary
To
calculate the length of a dictionary, we can use Python built-in
len() method. It method returns the number of keys in dictionary.
d
={'Name':'Steve', 'Age':30, 'Designation':'Programmer'}
print(len(d))
- Check if a Key Exists
Python dictionary can not contain duplicate
keys, so it is very crucial to check if a key is already present in the
dictionary. If you accidentally assign a duplicate key value, the new value
will overwrite the old one.
To check if given Key exists in dictionary,
you can use either in operator or get() method. Both are easy to use and work
efficiently.
Using IN operator
# Example dictionary
d = {'a': 1, 'b': 2, 'c': 3}
# Key to check
key = 'b'
print(key in d) # Output: True
key = 'g'
print(key in d) # Output: False
- Access a Value by Key
Retrieving
a value from a dictionary by its key is a common operation in many Python
programs. In this article, we will explore five simple and commonly used
methods to get a dictionary value by its key in Python.
# Creating
a sample dictionary
d =
{'name': 'geeks', 'age': 21, 'place': 'India'}
# Accessing
value using bracket notation
val =
d['name']
print("Name:",
val)
- Remove a Key from a Dictionary
We are given a dictionary and our task is to remove a specific key from it. For example, if we have the dictionary d = {“a”: 1, “b”: 2, “c”: 3}, then after removing the key “b”, the output will be {‘a’: 1, ‘c’: 3}.
Using pop()
pop()
method removes a specific key from the dictionary and returns its corresponding
value.
a =
{"name": "Nikki", "age": 25, "city":
"New York"}
# Remove
the key 'age'
rv = a.pop("age")
print(a)
print(rv)
Using del()
del() statement deletes a key-value pair from the
dictionary directly.
a =
{"name": "Nikki", "age": 25, "city":
"New York"}
# Delete
the key 'city'
del a["city"]
print(a)
Using
Dictionary Comprehension
Dictionary comprehension allows us to create a new
dictionary without the key we want to remove.
a =
{"name": "Nikki", "age": 25, "city":
"New York"}
# Remove
the key 'name' using dictionary comprehension
a = {k: v for k, v in a.items() if k != "name"}
print(a)
Using
popitem() for Last Key Removal
If we want
to remove the last key-value pair in the dictionary, popitem() is a quick way to do it.
a = {"name": "Nikki", "age": 25, "city": "New York"}
# Remove
the last key-value pair
c = a.popitem()
print(a)
print(c)
No comments:
Post a Comment