In this post, we'll explore how to use dictionaries in Python. We'll cover a range of topics, from creating and manipulating dictionaries to more advanced techniques such as sorting, merging, and using comprehension.
To create an empty dictionary, you can use the curly braces {}
or the dict()
function:
planets = {}
# or
planets = dict()
print(planets)
# Output: {}
The fromkeys
function allows you to create a dictionary with a set of keys and a default value for each key. For example, let's say we want to create a dictionary of planets with their distance from the sun in astronomical units (AU):
planets = dict.fromkeys(["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"], 0)
print(planets)
# Output: {'Mercury': 0, 'Venus': 0, 'Earth': 0, 'Mars': 0, 'Jupiter': 0, 'Saturn': 0, 'Uranus': 0, 'Neptune': 0}
To get the value associated with a key, you can use square brackets []
or the get
method. For example, to get the distance of Earth from the sun, you can do:
distance = planets["Earth"]
# or
distance = planets.get("Earth")
print(distance)
# Output: 0
To get the number of key-value pairs in a dictionary, you can use the len function:
size = len(planets)
print(size)
# Output: 8
To get a list of the keys in a dictionary, you can use the keys
method:
planet_names = planets.keys()
print(planet_names)
# Output: dict_keys(['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune'])
To get a list of the key-value pairs in a dictionary, you can use the items
method:
planet_distances = planets.items()
print(planet_distances)
# Output: dict_items([('Mercury', 0), ('Venus', 0), ('Earth', 0), ('Mars', 0), ('Jupiter', 0), ('Saturn', 0), ('Uranus', 0), ('Neptune', 0)])
To remove a key-value pair from a dictionary, you can use the pop
method. For example, to remove the entry for 'Pluto' from our dictionary, you can do:
planets.pop("Pluto", None)
print(planets.pop("Pluto", None))
# Output: None
To remove the last key-value pair added to the dictionary, you can use the popitem
method:
last_planet = planets.popitem()
print(last_planet)
# Output: ('Neptune', 0)
To delete all the key-value pairs in a dictionary, you can use the clear
method:
planets.clear()
print(planets)
# Output: {}
To delete the dictionary variable itself, you can use the del
statement:
del planets
You can also create a dictionary that groups elements from a list by length using the setdefault
method. This method allows you to set a default value for a key if it doesn't already exist in the dictionary. Here's an example using the same list of galaxies:
galaxies = ["Andromeda", "Milky Way", "Triangulum", "Large Magellanic Cloud", "Small Magellanic Cloud"]
galaxy_lengths = {}
for galaxy in galaxies:
length = len(galaxy)
galaxy_lengths.setdefault(length, []).append(galaxy)
print(galaxy_lengths)
# Output: {9: ['Andromeda', 'Triangulum'], 9: ['Milky Way'], 20: ['Large Magellanic Cloud', 'Small Magellanic Cloud']}
To sort a dictionary by value, you can use the sorted
function with a lambda function as the key argument. For example, let's say we have a dictionary of planets with their distance from the sun in astronomical units (AU):
planets = {"Mercury": 0.39, "Venus": 0.72, "Earth": 1.0, "Mars": 1.52, "Jupiter": 5.20, "Saturn": 9.58, "Uranus": 19.18, "Neptune": 30.07}
sorted_planets = sorted(planets.items(), key=lambda x: x)
print(sorted_planets)
# Output: [('Mercury', 0.39), ('Venus', 0.72), ('Earth', 1.0), ('Mars', 1.52), ('Jupiter', 5.2), ('Saturn', 9.58), ('Uranus', 19.18), ('Neptune', 30.07)]
To merge two dictionaries, you can use the update
method, the **
operator, the ChainMap
class from the collections module, or the |
operator (in Python 3.9 or later). Here are some examples:
# Using update
planets1 = {"Mercury": 0.39, "Venus": 0.72, "Earth": 1.0}
planets2 = {"Mars": 1.52, "Jupiter": 5.20, "Saturn": 9.58}
planets1.update(planets2)
print(planets1)
# Output: {'Mercury': 0.39, 'Venus': 0.72, 'Earth': 1.0, 'Mars': 1.52, 'Jupiter': 5.2, 'Saturn': 9.58}
Using **
planets1 = {"Mercury": 0.39, "Venus": 0.72, "Earth": 1.0}
planets2 = {"Mars": 1.52, "Jupiter": 5.20, "Saturn": 9.58}
merged_planets = {**planets1, **planets2}
print(merged_planets)
# Output: {'Mercury': 0.39, 'Venus': 0.72, 'Earth': 1.0, 'Mars': 1.52, 'Jupiter': 5.2, 'Saturn': 9.58}
Using ChainMap
from collections import ChainMap
planets1 = {"Mercury": 0.39, "Venus": 0.72, "Earth": 1.0}
planets2 = {"Mars": 1.52, "Jupiter": 5.20, "Saturn": 9.58}
merged_planets = ChainMap(planets1, planets2)
print(dict(merged_planets))
# Output: {'Mars': 1.52, 'Jupiter': 5.2, 'Saturn': 9.58, 'Mercury': 0.39, 'Venus': 0.72, 'Earth': 1.0}
Using |
planets1 = {"Mercury": 0.39, "Venus": 0.72, "Earth": 1.0}
planets2 = {"Mars": 1.52, "Jupiter": 5.20, "Saturn": 9.58}
merged_planets = planets1 | planets2
print(merged_planets)
# Output: {'Mercury': 0.39, 'Venus': 0.72, 'Earth': 1.0, 'Mars': 1.52, 'Jupiter': 5.2, 'Saturn': 9.58}
Finally, you can create a dictionary using comprehension. This allows you to create a dictionary in a single line of code using a for loop and an if statement. For example, let's say we have a list of planets with their distance from the sun in astronomical units (AU) and we want to create a dictionary of planets that are closer than 5 AU from the sun:
planet_distances = [("Mercury", 0.39), ("Venus", 0.72), ("Earth", 1.0), ("Mars", 1.52), ("Jupiter", 5.20), ("Saturn", 9.58), ("Uranus", 19.18), ("Neptune", 30.07)]
close_planets = {planet: distance for planet, distance in planet_distances if distance < 5}
print(close_planets)
# Output: {'Mercury': 0.39, 'Venus': 0.72, 'Earth': 1.0, 'Mars': 1.52}
This creates a dictionary with the keys "Mercury", "Venus", "Earth", and "Mars", and their corresponding distances from the sun as the values.
That concludes our exploration of dictionaries in Python with an astronomy theme. We hope you found this post informative and helpful!
Top comments (0)