Python – Dictionary

By | 28/08/2019

In this post, we will see how to manage Dictionary with Python.

CREATE A DICTIONARY

# empty dictionary
dict1 ={}

# dictionary
dict2 = {1:"one", 2:"two", 3:"three"}

print(f"dictionary1:  {dict1}")
print(f"dictionary2:  {dict2}")



ADD ITEMS

# empty dictionary
dict1 ={}

# dictionary
dict2 = {1:"one", 2:"two", 3:"three"}

print(f"dictionary1:  {dict1}")
print(f"dictionary2:  {dict2}")

# add items
dict1[1]='one'
dict1[2]='two'
dict2[4]='four'
dict2[5]='five'

print(f"dictionary1:  {dict1}")
print(f"dictionary2:  {dict2}")



UPDATE ITEMS

# dictionary
dict1 = {1:"one", 2:"two", 3:"three"}

print(f"dictionary1:  {dict1}")

#update value
dict1[1]='NewOne'

print(f"dictionary1:  {dict1}")



DELETE ITEMS

# dictionary
dict1 = {1:"one", 2:"two", 3:"three"}

print(f"dictionary1:  {dict1}")

#delete value using the key
del dict1[3]

print(f"dictionary1:  {dict1}")



GET VALUES

# dictionary
dict1 = {1:"one", 2:"two", 3:"three"}

print("Dictionary: ", dict1)

# get value using the key
print(f"Value with key equal to 2: {dict1[2]}")

# With the method get, in case of key not present, the system 
# will show a default value instead to generate an error
print(f"Key not present into dictionary: {dict1.get(5,'Key not present')}")

# print all items in a dictionary
for i in dict1:              
    print(f"Key: {i} - Value: {dict1[i]}")





Leave a Reply

Your email address will not be published. Required fields are marked *