Dictionary in Python1
Dictionary in Python1
Output
{1: ‘Hello', 2: ‘Welcome', 3: ‘Pyton‘,3:”Dictionary”}
Python Dictionary Syntax
The addition of elements can be done in multiple ways. One value at a time can be added to a
Dictionary by defining value along with the key e.g. Dict[Key] = ‘Value’.
Updating an existing value in a Dictionary can be done by using the built-in update() method.
Nested key values can also be added to an existing Dictionary.
Note- While adding a value, if the key-value already exists, the value gets updated otherwise a
new Key with the value is added to the Dictionary.
Example: Add Items to a Python Dictionary with Different DataTypes
The code starts with an empty dictionary and then adds key-value pairs to it. It demonstrates
adding elements with various data types, updating a key’s value, and even nesting dictionaries
within the main dictionary. The code shows how to manipulate dictionaries in Python.
Dict = {}
print("Empty Dictionary: ")
print(Dict)
Dict[0] = 'Geeks'
Dict[2] = 'For'
Dict[3] = 1
print("\nDictionary after adding 3 elements: ")
print(Dict)
Dict['Value_set'] = 2, 3, 4
print("\nDictionary after adding 3 elements: ")
print(Dict)
Dict[2] = 'Welcome'
print("\nUpdated key value: ")
print(Dict)
Dict[5] = {'Nested': {'1': 'Life', '2': 'Geeks'}}
print("\nAdding a Nested Key: ")
print(Dict)
Dictionary Methods
Here is a list of in-built dictionary functions with their description. You can use these functions to
operate on a dictionary.
Method Description
dict.items() Returns a list containing a tuple for each key value pair
set the key to the default value if the key is not specified in
dict.setdefault(key,default= “None”)
the dictionary