dictionary function in python code example
Example 1: dictionary in python
tel = {'jack': 4098, 'sape': 4139}
tel['guido'] = 4127
print(tel)
print(tel['jack'])
del tel['sape']
tel['irv'] = 4127
print(tel)
print(list(tel))
print(sorted(tel))
print('guido' in tel)
print('jack' not in tel)
Example 2: all dictionary functions in python
clear() - Removes all the elements from the dictionary
copy() - Returns a copy of the dictionary
fromkeys() - Returns a dictionary with the specified keys and value
get() - Returns the value of the specified key
items() - Returns a list containing a tuple for each key value pair
keys() - Returns a list containing the dictionary's keys
pop() - Removes the element with the specified key
popitem() - Removes the last inserted key-value pair
setdefault() - Returns the value of the specified key. If the key does not exist: insert the key, with the specified value
update() - Updates the dictionary with the specified key-value pairs
values() - Returns a list of all the values in the dictionary
Example 3: dictionary in python
d = {'key1':'value1','key2':'value2'}
print(d)
l=d.keys
print(l)
b=d.values
print(b)
Example 4: python dictionary functions
clear() - Removes all the elements from the dictionary
copy() - Returns a copy of the dictionary
fromkeys() - Returns a dictionary with the specified keys and value
get() - Returns the value of the specified key
items() - Returns a list containing a tuple for each key value pair
keys() - Returns a list containing the dictionary's keys
pop() - Removes the element with the specified key
popitem() - Removes the last inserted key-value pair
setdefault() - Returns the value of the specified key. If the key does not exist: insert the key, with the specified value
update() - Updates the dictionary with the specified key-value pairs
values() - Returns a list of all the values in the dictionary
Example 5: dictionary in python
my_dict = {"Key": "Value"}
print(my_dict["Key"])
my_animals = {"Dog": "Percy",
"Cat": "Fluffy",
"Turtle": "Bennedict"}
for animal in my_animals:
print(my_animals[animal])