Python dictionary
A Python dictionary is a built-in data structure that stores a collection of key-value pairs. It is also known as an associative array or hash table in other programming languages. Dictionaries are unordered, meaning the elements are not stored in a specific order, and they are mutable, allowing you to add, modify, and remove items.
Here’s an example of a Python dictionary:
person = { "name": "John", "age": 30, "city": "New York" }
In this example, "name"
, "age"
, and "city"
are the keys, and "John"
, 30
, and "New York"
are the corresponding values. You can access the values by providing the key in square brackets:
print(person["name"])
# Output: JohnYou can also modify the values associated with keys or add new key-value pairs:
person["age"] = 31 # Modifying the value
person["occupation"] = "Engineer" # Adding a new key-value pair
print(person) # Output: {'name': 'John', 'age': 31, 'city': 'New York', 'occupation': 'Engineer'}
To check if a key exists in the dictionary, you can use the in
operator:
if "name" in person: print("Name exists in the dictionary.")
You can iterate over the keys or values of a dictionary using loops or perform operations like getting the number of items in the dictionary using the len()
function.
for key in person: print(key, person[key])
# Output: name John,
age 31, city New York,
occupation Engineer
print(len(person)) # Output: 4
Python dictionaries are versatile data structures that are widely used for mapping and storing data based on keys for efficient retrieval.