Example 1: python dictionary
dict1 = {'color': 'blue', 'shape': 'square', 'volume':40}
dict2 = {'color': 'red', 'edges': 4, 'perimeter':15}
dict1['area'] = 25
dict2['perimeter'] = 20
print(dict1['shape'])
dict1.get('false_key')
dict1.get('false_key', "key not found")
dict1.pop('volume')
dict1.update(dict2)
dict1
dict1.values()
dict1.keys()
dict1.items()
Example 2: python dictionary
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
Example 3: python dict
my_dict = {
'spam': 'eggs',
'foo': 4,
100: 'bar',
2: 0.5
}
print(my_dict['spam'])
print(my_dict['foo'])
print(my_dict[100])
print(my_dict[2])
for key, value in my_dict.items():
print(key, value)
print(len(my_dict))
my_dict['baz'] = 'qux'
my_dict['baz'] = 'quxx'
del my_dict['spam']
print(my_dict.copy())
print(my_dict.fromkeys('added', 100))
print(my_dict.get('foo'))
print(my_dict.items())
print(my_dict.keys())
print(my_dict.values())
my_dict.setdefault('a', 'b')
my_dict.pop('foo')
my_dict.popitem()
my_dict.update({'baz': 'val'})
my_dict.clear()
Example 4: dictionaries in python 3
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: python dictionary
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
Example 6: python dictionary
dict1 = {'color': 'blue', 'shape': 'square', 'volume':40}
dict2 = {'color': 'red', 'edges': 4, 'perimeter':15}