GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing www.tutorialspoint.com — Python - Dictionaries
Selected Reading
Python - DictionariesDictionaries in PythonIn Python, a dictionary is a built-in data type that stores data in key-value pairs. It is an insertion-ordered and mutable collection. Each key must be unique and hashable, and values can be accessed using their corresponding keys. Dictionaries are often used to store data that is related, such as information associated with a specific entity or object, where you can quickly retrieve a value based on its key. Python's dictionary is an example of a mapping type. A mapping object 'maps' the value of one object to another. To establish mapping between a key and a value, the colon (:) symbol is put between the two. Each key-value pair is separated by a comma and enclosed within curly braces {}. The key and value within each pair are separated by a colon (:), forming the structure key:value. Given below are some examples of Python dictionary objects − capitals = {"Maharashtra":"Mumbai", "Gujarat":"Gandhinagar", "Telangana":"Hyderabad", "Karnataka":"Bengaluru"}
numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}
marks = {"Savita":67, "Imtiaz":88, "Laxman":91, "David":49}
Key Features of DictionariesFollowing are the key features of dictionaries −
Example 1Only hashable objects can be used as keys, such as a number, string or tuple (containing only hashable elements). You can use an object of any type as the value. Hence following definitions of dictionary are also valid − d1 = {"Fruit":["Mango","Banana"], "Flower":["Rose", "Lotus"]}
d2 = {('India, USA'):'Countries', ('New Delhi', 'New York'):'Capitals'}
print (d1)
print (d2)
It will produce the following output − {'Fruit': ['Mango', 'Banana'], 'Flower': ['Rose', 'Lotus']}
{'India, USA': 'Countries', ('New Delhi', 'New York'): 'Capitals'}
Example 2Python doesn't accept unhashable objects such as list as key, and raises TypeError. d1 = {["Mango","Banana"]:"Fruit", "Flower":["Rose", "Lotus"]}
print (d1)
It will raise a TypeError − Traceback (most recent call last):
File "C:\Users\Sairam\PycharmProjects\pythonProject\main.py", line 8, in <module>
d1 = {["Mango","Banana"]:"Fruit", "Flower":["Rose", "Lotus"]}
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: unhashable type: 'list'
Example 3You can assign a value to more than one keys in a dictionary, but a key cannot appear more than once in a dictionary. d1 = {"Banana":"Fruit", "Rose":"Flower", "Lotus":"Flower", "Mango":"Fruit"}
d2 = {"Fruit":"Banana","Flower":"Rose", "Fruit":"Mango", "Flower":"Lotus"}
print (d1)
print (d2)
It will produce the following output − {'Banana': 'Fruit', 'Rose': 'Flower', 'Lotus': 'Flower', 'Mango': 'Fruit'}
{'Fruit': 'Mango', 'Flower': 'Lotus'}
Creating a DictionaryYou can create a dictionary in Python by placing a comma-separated sequence of key-value pairs within curly braces {}, with a colon : separating each key and its associated value. Alternatively, you can use the dict() function. ExampleThe following example demonstrates how to create dictionaries using both curly braces and the dict() function − # Creating a dictionary using curly braces
sports_player = {
"Name": "Sachin Tendulkar",
"Age": 48,
"Sport": "Cricket"
}
print ("Dictionary using curly braces:", sports_player)
# Creating a dictionary using the dict() function
student_info = dict(name="Alice", age=21, major="Computer Science")
print("Dictionary using dict():",student_info)
The result produced is as shown below − Dictionary using curly braces: {'Name': 'Sachin Tendulkar', 'Age': 48, 'Sport': 'Cricket'}
Dictionary using dict(): {'name': 'Alice', 'age': 21, 'major': 'Computer Science'}
Accessing Dictionary ItemsYou can access the value associated with a specific key using square brackets [] or the get() method − student_info = {
"name": "Alice",
"age": 21,
"major": "Computer Science"
}
# Accessing values using square brackets
name = student_info["name"]
print("Name:",name)
# Accessing values using the get() method
age = student_info.get("age")
print("Age:",age)
The result obtained is as follows − Name: Alice Age: 21 Modifying Dictionary ItemsYou can modify the value associated with a specific key or add a new key-value pair − student_info = {
"name": "Alice",
"age": 21,
"major": "Computer Science"
}
# Modifying an existing key-value pair
student_info["age"] = 22
# Adding a new key-value pair
student_info["graduation_year"] = 2023
print("The modified dictionary is:",student_info)
Output of the above code is as follows − The modified dictionary is: {'name': 'Alice', 'age': 22, 'major': 'Computer Science', 'graduation_year': 2023}
Removing Dictionary ItemsYou can remove items using the del statement, the pop() method, or the popitem() method − student_info = {
"name": "Alice",
"age": 22,
"major": "Computer Science",
"graduation_year": 2023
}
# Removing an item using the del statement
del student_info["major"]
# Removing an item using the pop() method
graduation_year = student_info.pop("graduation_year")
print(student_info)
Following is the output of the above code − {'name': 'Alice', 'age': 22}
Iterating Through a DictionaryYou can iterate through the keys, values, or key-value pairs in a dictionary using loops − student_info = {
"name": "Alice",
"age": 22,
"major": "Computer Science",
"graduation_year": 2023
}
# Iterating through keys
for key in student_info:
print("Keys:",key, student_info[key])
# Iterating through values
for value in student_info.values():
print("Values:",value)
# Iterating through key-value pairs
for key, value in student_info.items():
print("Key:Value:",key, value)
After executing the above code, we get the following output − Keys: name Alice Keys: age 22 Keys: major Computer Science Keys: graduation_year 2023 Values: Alice Values: 22 Values: Computer Science Values: 2023 Key:Value: name Alice Key:Value: age 22 Key:Value: major Computer Science Key:Value: graduation_year 2023 Properties of Dictionary KeysDictionary values have no restrictions. They can be any arbitrary Python object, either standard objects or user-defined objects. However, same is not true for the keys. There are two important points to remember about dictionary keys −
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}
print ("dict['Name']: ", dict['Name'])
When the above code is executed, it produces the following result − dict['Name']: Manni dict = {['Name']: 'Zara', 'Age': 7}
print ("dict['Name']: ", dict['Name'])
When the above code is executed, it produces the following result − Traceback (most recent call last):
File "test.py", line 3, in <module>
dict = {['Name']: 'Zara', 'Age': 7};
TypeError: unhashable type: 'list'
Python Dictionary OperatorsIn Python, following operators are defined to be used with dictionary operands. In the example, the following dictionary objects are used. d1 = {'a': 2, 'b': 4, 'c': 30}
d2 = {'a1': 20, 'b1': 40, 'c1': 60}
Python Dictionary MethodsPython includes following dictionary methods −
Built-in Functions with DictionariesFollowing are the built-in functions we can use with Dictionaries −
Advertisements
| ||||||||||||||||||||||||||||||||||||||||
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |