xxxxxxxxxx
# Creating a sample dictionary
person = {
'name': 'John',
'age': 30,
'gender': 'Male'
}
# Accessing dictionary keys
keys = person.keys()
# Printing the keys
print(keys)
xxxxxxxxxx
#Creating dictionaries
dict1 = {'color': 'blue', 'shape': 'square', 'volume':40}
dict2 = {'color': 'red', 'edges': 4, 'perimeter':15}
#Creating new pairs and updating old ones
dict1['area'] = 25 #{'color': 'blue', 'shape': 'square', 'volume': 40, 'area': 25}
dict2['perimeter'] = 20 #{'color': 'red', 'edges': 4, 'perimeter': 20}
#Accessing values through keys
print(dict1['shape'])
#You can also use get, which doesn't cause an exception when the key is not found
dict1.get('false_key') #returns None
dict1.get('false_key', "key not found") #returns the custom message that you wrote
#Deleting pairs
dict1.pop('volume')
#Merging two dictionaries
dict1.update(dict2) #if a key exists in both, it takes the value of the second dict
dict1 #{'color': 'red', 'shape': 'square', 'area': 25, 'edges': 4, 'perimeter': 20}
#Getting only the values, keys or both (can be used in loops)
dict1.values() #dict_values(['red', 'square', 25, 4, 20])
dict1.keys() #dict_keys(['color', 'shape', 'area', 'edges', 'perimeter'])
dict1.items()
#dict_items([('color', 'red'), ('shape', 'square'), ('area', 25), ('edges', 4), ('perimeter', 20)])
xxxxxxxxxx
#title :Dictionary Example
#author :Josh Cogburn
#date :20191127
#github :https://github.com/josh-cogburn
#====================================================
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
#Assigning a value
thisdict["year"] = 2018
xxxxxxxxxx
# Dictionary with three keys
Dictionary1 = {'A': 'Geeks', 'B': 'For', 'C': 'Geeks'}
# Printing keys of dictionary
print(Dictionary1.keys())
xxxxxxxxxx
# dictionary refresh
new_dict = {
"first":"1,2,3",
"second":"321",
"third":"000",
}
# adding to dictionary
new_dict.update({"fourth":"D"})
print(new_dict)
#removing from dictionary
new_dict.pop("first")
print(new_dict)
new = {"five":"888"}
#updating a dictionary
new_dict.update(new)
print(new_dict)
xxxxxxxxxx
my_dict = {"apple": 4, "banana": 2, "orange": 5, "mango": 3}
keys = list(my_dict.keys())
print(keys)
xxxxxxxxxx
human = {
"code": "Python",
"name": "John",
"age": 32
}
print(human["age"])
#32 :D
xxxxxxxxxx
dictionary = {
"name": "Elie",
"family name": "Carcassonne",
"date of born": "01/01/2001",
"list": ["hey", "hey"]
}
xxxxxxxxxx
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Geeks', 2: 'For', 3:'Geeks'})
print("\nDictionary with the use of dict(): ")
print(Dict)
# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, 'Geeks'), (2, 'For')])
print("\nDictionary with each item as a pair: ")
print(Dict)