Python Dictionaries: Storing Key-Value Pairs


Python dictionaries are a collection of key-value pairs. They are unordered, changeable, and do not allow duplicate keys. Dictionaries are written with curly brackets {}, and consist of keys and values separated by a colon :.

Here is an example of a dictionary:

Copy code
person = {
  "name": "John",
  "age": 30,
  "city": "New York"
}
To access the values in a dictionary, you can use the keys in square brackets []. For example:

Copy code
name = person["name"]
age = person["age"]
city = person["city"]

print(name) # Output: "John"
print(age) # Output: 30
print(city) # Output: "New York"
You can also use the get() method to access the values in a dictionary. This is useful when you want to set a default value if the key does not exist. For example:

Copy code
name = person.get("name", "unknown")
age = person.get("age", "unknown")
city = person.get("city", "unknown")

print(name) # Output: "John"
print(age) # Output: 30
print(city) # Output: "New York"
To add a new key-value pair to a dictionary, you can use the assignment operator (=). For example:

Copy code
person["profession"] = "software developer"

print(person)
# Output: {'name': 'John', 'age': 30, 'city': 'New York', 'profession': 'software developer'}
To remove a key-value pair from a dictionary, you can use the pop() method. This method removes the key-value pair from the dictionary and returns the value. If the key does not exist, it returns a default value. For example:

Copy code
profession = person.pop("profession", "unknown")

print(profession) # Output: "software developer"
print(person) # Output: {'name': 'John', 'age': 30, 'city': 'New York'}
You can also use the popitem() method to remove a random key-value pair from a dictionary. This method removes the key-value pair from the dictionary and returns it as a tuple. For example:

Copy code
key_value_pair = person.popitem()

print(key_value_pair) # Output: ("city", "New York")
print(person) # Output: {'name': 'John', 'age': 30}
To update the values in a dictionary, you can use the assignment operator (=). This will overwrite the existing values with the new values. For example:

Copy code
person["name"] = "Jane"
person["age"] = 25

print(person) # Output: {'name': 'Jane', 'age': 25}
You can also use the update() method to update the values in a dictionary. This method takes a dictionary as an argument and updates the values in the original dictionary. For example:

Copy code
new_info = {
  "name": "John",
  "age": 30,
  "country": "USA"
}

person.update(new_info)

Comments