python set dict value code example

Example 1: how to set a key of dict in python

# declaring dict
dictionary={'Hello':3,'World!':4}
# creating function
def dict_add(obj,key,value):
  obj[key]=value
  reutrn obj
# using the functiom
dict_add(dictionary,'Python',10)
print (dictionary) # output --> { 'Hello':3 ,'World!':4 , 'Python':10 }

Example 2: how to get element from dictionary python

#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry

print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']

Example 3: how to modify the dict in python

d = {1: "one", 2: "three"}
d1 = {2: "two"}

# updates the value of key 2
d.update(d1)
print(d)

d1 = {3: "three"}

# adds element with key 3
d.update(d1)
print(d)

Example 4: python dictionary value as set

word_dict = dict()
word_dict["foo"] = set()
word_dict["foo"].add("baz")                                    
word_dict["foo"].add("bang")