A dictionary in Python is a collection of key-value pairs. Each key is unique and maps to a value. Dictionaries are mutable, meaning they can be changed after they are created. They are defined using curly braces {}
and key-value pairs are separated by a colon :
.
Python dictionary is an unordered collection of items. In a dictionary, each item has a key/value pair.
Creating a Dictionary
You can create a dictionary by placing a comma-separated sequence of key-value pairs within curly braces.
Example:
users = {'name':'Junaid', 'age':25, 'city' : 'Nashik'} print(users) print(type(users)) user_info = { 'name' : 'Junaid Shaikh', 'age' : 24, 'skills' : ['a', 'v'], 'tunes' : ['t', 'tv'], } print(user_info['skills'])
Accessing Values
You can access the value associated with a key using square brackets []
.
# access data from dictionaries
print(users['name'])
Modifying Values
You can modify the value associated with a key by assigning a new value to that key.
# Modifying values in a dictionary
users["age"] = 26
print(users["age"]) # Output: 26
Adding New Key-Value Pairs
You can add a new key-value pair to a dictionary by simply assigning a value to a new key.
# Adding new key-value pairs
users["email"] = "infovistarindia@gmail.com"
print(users)
Removing Key-Value Pairs
You can remove a key-value pair using the del
statement or the pop()
method.
# Removing key-value pairs
del users["city"]
print(users)
# Using pop() method
age = users.pop("age")
print(age) # Output: 26
print(users)
Iterating Over a Dictionary
You can iterate over the keys, values, or key-value pairs in a dictionary.
# Iterating over keys
for key in users:
print(key, users[key])
# Iterating over values
for value in users.values():
print(value)
# Iterating over key-value pairs
for key, value in users.items():
print(key, value)
Dictionary Methods
Python dictionaries come with several built-in methods. Here are a few useful ones:
Function | Description |
---|---|
dict.clear() | removes all elements of dictionary dict |
dict.copy() | returns a shallow copy of dictionary dict |
dict.items() | returns a list of dict’s (key, value) tuple pairs |
dict.setdeafult(key, default=Nonre) | similiar to get(), but will set dict[key] = default |
dict.update(dict2) | adds dictionary dict2’s key-values pairs to dict |
dict.keys() | returns list of dictionary dict’s keys |
dict.values() | returns list of dictionary dict’s values |
# Using dictionary methods
print(users.get("name")) # Output: Junaid
print(users.get("address", "Address not found")) # Output: Address not found
print(list(users.keys())) # Output: ['name', 'email']
print(list(users.values())) # Output: ['Junaid', 'infovistarindia@gmail.com']
print(list(users.items())) # Output: [('name', 'Junaid'), ('email', 'infovistarindia@gmail.com')]