Dictionary in Python
In Python, a dictionary is an unordered collection of items, with each item consisting of a key and a value. Dictionaries are used to store data values in a key-value pair format, with the keys serving as unique identifiers for the values.
Dictionaries in Python |
Here is an example of how you can create a dictionary in Python:
my_dict = {'key1': 'value1', 'key2': 'value2'}
You can also use the dict() function to create a dictionary:
my_dict = dict(key1='value1', key2='value2')
To access the values in a dictionary, you can use the keys as indexes, like this:
value1 = my_dict['key1']
value2 = my_dict['key2']
You can also use the get() method to retrieve the value for a given key:
value1 = my_dict.get('key1')
value2 = my_dict.get('key2')
To add a new key-value pair to a dictionary, you can use the assignment operator:
my_dict['key3'] = 'value3'
To remove a key-value pair from a dictionary, you can use the del statement:
del my_dict['key3']
You can also use the pop() method to remove a key-value pair from a dictionary and return the value:
value3 = my_dict.pop('key3')
To iterate over the keys and values in a dictionary, you can use the items() method:
for key, value in my_dict.items():
print(key, value)
To get a list of all the keys in a dictionary, you can use the keys() method:
keys = my_dict.keys()
To get a list of all the values in a dictionary, you can use the values() method:
values = my_dict.values()
Accessing Dictionary Values in python
To access a value in a dictionary, you can use the following syntax:
dictionary_name[key]
For example, if you have a dictionary called student with a key "name" and a value "John", you can access the value by using the following code:
name = student["name"]
print(name)
If the key does not exist in the dictionary, you will get a KeyError. You can use the in keyword to check if a key exists in the dictionary before attempting to access the value. For example:
if "name" in student:
name = student["name"]
print(name)
else:
print("Key not found in dictionary.")
You can also use the get() method to access values in a dictionary. This method returns the value for the given key, or a default value if the key is not found. For example:
name = student.get("name", "unknown")
print(name)
This would output "name" if the key name exists in the dictionary, and "unknown" if it does not.
Create your first application with Python
Type Casting in Python
0 Comments