xxxxxxxxxx
#title : Dictionary Example
#author : Joyiscold
#date : 2020-02-01
#====================================================
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
#Assigning a value
thisdict["year"] = 2018
xxxxxxxxxx
""" In a dictionary, the first value of an element is the *key* and
the other one is the *value* """
new_dict = {
'name': 'Alex',
'age': 21
}
""" You can also use different data type for key in the same dictionary """
new_dict = {
'name': 'Alex',
1: 21,
2: False
}
xxxxxxxxxx
thisdict = {
"key1" : "value1"
"key2" : "value2"
"key3" : "value3"
"key4" : "value4"
}
xxxxxxxxxx
hh = {"john":3, "mary":4, "joe":5}
print(hh)
# {'joe': 5, 'john': 3, 'mary': 4}
xxxxxxxxxx
myDict = {'first item' : 'definition'}
#CREATING A BLANK DICTIONARY
myDict = {}
xxxxxxxxxx
# Creating a dictionary with integer keys and string values
dict1 = {1: 'red', 2: 'green', 3: 'blue'}
# Creating a dictionary with string keys and integer values
dict2 = {'red': 1, 'green': 2, 'blue': 3}
# Creating a dictionary with mixed data types
dict3 = {'name': 'John', 'age': 30, 'city': 'New York'}
# Creating an empty dictionary
dict4 = {}
# Creating a dictionary from a list of tuples
list1 = [('red', 1), ('green', 2), ('blue', 3)]
dict5 = dict(list1)
# Creating a dictionary from keyword arguments
dict6 = dict(red=1, green=2, blue=3)
# Accessing the value of the 'name' key in dict3
value = dict3['name']
# Accessing the value of the 2 key in dict1
value = dict1[2]
# Accessing the value of the 'city' key in dict3
value = dict3.get('city', 'unknown')
# Accessing the value of the 'country' key in dict3
value = dict3.get('country', 'unknown')
# Getting a list of all the keys in dict3
keys = dict3.keys()
# Getting a list of all the values in dict3
values = dict3.values()
# Printing the dictionaries
print(dict1)
print(dict2)
print(dict3)
print(dict4)
print(dict5)
print(dict6)
# Printing the value, keys, and values
print(value)
print(keys)
print(values)
# Determining the data type of a dictionary
print(type(dict1)) # prints "<class 'dict'>"
xxxxxxxxxx
# Creating a Dictionary
# with Integer Keys
Dictionary = {0: 'Softhunt', 1: '.net', 2: 'By', 3: 'Ranjeet'}
print("\nDictionary with the use of Integer Keys: ")
print(Dictionary)
# Creating a Dictionary
# with Mixed keys
Dictionary = {'Name': 'Ranjeet Kumar Andani', 1: [0, 1, 2, 3, 4, 5]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dictionary)
xxxxxxxxxx
d = {'key': 'value'}
print(d)
# {'key': 'value'}
d['mynewkey'] = 'mynewvalue'
print(d)
# {'key': 'value', 'mynewkey': 'mynewvalue'}