Python Dictionary is awesome

Dictionary

A dictionary in Python is an unordered collection of key-value pairs. It is a mutable, indexed, and iterable data structure that is commonly used to store and retrieve data. The keys in a dictionary must be unique and immutable (strings, integers, tuples) while the values can be of any data type (strings, integers, lists, sets, other dictionaries, etc.). It could be create by my_dict = {"name": "John", "age": 25, "city": "New York"}

Here is some basic operations for Python dictionary

  1. Creating a dictionary
my_dict = {"name": "John", "age": 25, "city": "New York"}
  1. Accessing values using keys
print(my_dict["name"]) 
print(my_dict["age"])
John
25
  1. Adding a new key-value pair
my_dict["country"] = "USA"
print(my_dict)
{"name": "John", "age": 25, "city": "New York", "country": "USA"}
  1. Removing and Updating
del my_dict["city"]
my_dict["age"] = 26
  1. Checking if a key exists in a dictionary
if "name" in my_dict:
print("Name is present")
else:
print("Name is not present")

# Iterating through a dictionary
for key, value in my_dict.items():
print(key, value)

Find the max value from a dictionary

d = {'a': 10, 'b': 5, 'c': 20}
max_value = max(d, key=d.get)
print(max_value)
c
Author

Karobben

Posted on

2023-03-01

Updated on

2024-01-11

Licensed under

Comments