Dictionary Data Type In Python
What is Dictionary Data Type?
Dictionary
is a built in data type which allows us key-value pair. It is also referred as
associative array or hash table. The dictionary is unordered and mutable data
structure which helps us to store and access data associated with their keys. The
key of dictionary should be unique and immutable. Your key may be string,
number or tuple. Values can be of any type. The dictionary data items are
enclosed within pair of curly brackets and key and value are separated with
colon (:). The dictionary are used to map to data sets such as roll number and
name of students or keyword and its definition, person name and their phone
number.
How
to Create Dictionary:
1.
my_dict={'fruit1':'apple','fruit2':'banana'}
print(my_dict)
Output:
{'fruit1':
'apple', 'fruit2': 'banana'}
In
the above example my_dict is dictionary name and fruit1, fruit2 are the keys
with its values apple and banana respectively. In this example both key and
values are string type.
2.
my_dict={1:'apple',2:'banana'}
print(my_dict)
Output:
{1:
'apple', 2: 'banana'}
In
this example dictionary is created with keys 1,2 are the numeric type and
values are string type.
3.
my_dict={'apple':1,'banana':2}
my_dict
Output:
{'apple':
1, 'banana': 2}
In
this example dictionary is created with key string type and values are numeric
type. Here apple and banana are keys and 1,2 are values.
4.
Dictionary
with dict keyword:
my_dict=dict(apple=1,banana=2,carrot=3,flower=4)
print(my_dict)
{'apple':
1, 'banana': 2, 'carrot': 3, 'flower': 4}
In
this example we have created dictionary with dict keyword. Here curly bracket
is not used to enclose the dictionary. Because the dict() it is builtin
function and function come with pair of parenthesis. In dict() parenthesis the
key value pair is stored.
How to Access Dictionary Elements:?
my_dict={'apple':1,'banana':2}
print(my_dict['apple'])
Output:
1
We
can access the values of dictionary by using key. In above example apple is key and we have
accessed its value 1 by accessing key apple.
Another Example,
my_dict={'fruit1':'apple','fruit2':'banana'}
print(my_dict['fruit1'])
Output:
Apple
Here
we have accessed apple value through the key fruit1. In the above example only one value is
accessed by using key name in square bracket. But if we want to access all
values from the dictionary then we can use loop.
For Loop to Access all values from
Dictionary:
my_dict1={"fruit1":"Apple","Fruit2":"Banana"}
for
key in my_dict1:
print(my_dict1[key])
Output:
Apple
Banana
Here
all keys are accessed with for loop and in this way we can access values of
keys. He key is loop variable which is used to access keys.
Another
example,
dict1={1:10,2:20,3:30,4:40,5:50,6:60}
for
key in dict1:
print(key,dict1[key])
Output:
1
10
2
20
3
30
4
40
5
50
6
60
Here
we have accessed all keys and in square bracket again given key so compiler
will access all values associated with keys.
List of Methods/ Functions used for Dictionary:
1. Len() Function:
The
len() method return the number of key values pair from dictionary.
For
example,
dict1={1:"banana",2:"Apple",3:"Grapes","Fruits":"Pineapple"}
print(len(dict1))
Output:
4
In
above dictionary total 4 key-value pairs stored in dictionary. So len() function
returned 4 as an output.
2.
Keys() Method:
The
keys() method returns list of all the keys present in your dictionary.
For
example,
dict1={1:"banana",2:"Apple",3:"Grapes","Fruits":"Pineapple"}
print(dict1.keys())
Output:
dict_keys([1,
2, 3, 'Fruits'])
3.
The values() Method:
The
values() function returns list of all the values in your dictionary.
For
example,
dict1={1:"banana",2:"Apple",3:"Grapes","Fruits":"Pineapple"}
print(dict1.values())
Output:
dict_values(['banana',
'Apple', 'Grapes', 'Pineapple'])
4. The items() Method:
This
function returns list of all key-value pairs.
For
example,
dict1={1:"banana",2:"Apple",3:"Grapes","Fruits":"Pineapple"}
print(dict1.items())
Output:
dict_items([(1,
'banana'), (2, 'Apple'), (3, 'Grapes'), ('Fruits', 'Pineapple')])
5. The get() Method:
The
get() method is used to get a specified key’s value.
For
example,
dict1={1:"banana",2:"Apple",3:"Grapes","Fruits":"Pineapple"}
print(dict1.get(1))
print(dict1.get("fruits"))
Output:
banana
None
In
this example in first print function with the get method passed value 1 i.e. 1
is a key present in dictionary dict1. And its associated value is banana. So
compiler has displayed banana as an output.
In
second print function with get() passed the key fruits. But fruits key not
present, Fruit key is present so compiler has displayed None.
6. The pop():
The
pop() function removes a specified key-value pair from dictionary. For example,
dict1={1:"banana",2:"Apple",3:"Grapes","Fruits":"Pineapple"}
print(dict1.pop(2))
print(dict1)
Output:
Apple
{1:
'banana', 3: 'Grapes', 'Fruits': 'Pineapple'}
In
above example pop function is applied on dict1 dictionary. In pop() function 2
is passed. This is the key in your dictionary and its associated value is
Apple. When you display your dictionary after
applying pop function then it will not display Apple value.
7. The update():
This
function helps to update the key value pair from dictionary.
dict1={1:"banana",2:"Apple",3:"Grapes","Fruits":"Pineapple"}
dict1.update({2:"Apple1"})
print(dict1)
Output:
{1:
'banana', 2: 'Apple1', 3: 'Grapes', 'Fruits': 'Pineapple'}
In
the parenthesis of update function, the second key 2 has updated with Apple1.
Its old value is Apple.
8. The clear():
The
clear() function helps to clear your dictionary. It helps to remove all key
values pairs from dictionary.
For
example,
dict2={1:"banana",2:"Apple",3:"Grapes","Fruits":"Pineapple"}
dict2.clear()
print(dict2)
Output:
{}
The
compiler will return empty dictionary.
For Loop on keys():
dict1={1:10,2:20,3:30,4:40,5:50,6:60,7:13,8:"Hello"}
for
key in dict1.keys():
print(key)
1
2
3
4
5
6
7
8
The
keys() helps to access all keys.
For Loop on items():
dict1={1:10,2:20,3:30,4:40,5:50,6:60,7:13,8:"Hello"}
for
key,value in dict1.items():
print(key,value)
Output:
1 10
2 20
3 30
4 40
5 50
6 60
7 13
8 Hello
For Loop on values():
dict1={1:10,2:20,3:30,4:40,5:50,6:60,7:13,8:"Hello"}
for key in
dict1.values():
print(key)
10
20
30
40
50
60
13
Hello
Python program to print the sum of all values in
Dictionary
dict1={1:10,2:20,3:30,4:40,5:50,6:60,7:13,8:"Hello"}
sum=0
for i in
dict1.values():
if isinstance(i,int):
sum=sum+i
print("The
sum of all values in dictionary is:",sum)
Output:
The sum of all
values in dictionary is: 223
In
above code isinstance() function is used to include only integer values from
dictionary. In our dictionary the 8th key have string value but on
string value the addition is not possible. So isinstance() method is applied on
dictionary in in parenthesis the loop variable I and int keyword is passed. So
now when compiler will execute the code by taking only the numeric values.
User Input for Dictionary:
my_dict
= {} #Empty dictionary
n
= int(input("Enter the number of key-value pairs: "))
for
i in range(n):
key = input("Enter the key: ")
value = input("Enter the value:
")
my_dict[key] = value
print("My
dictionary is:", my_dict)
Output:
Enter
the number of key-value pairs: 3
Enter
the key: DBMS
Enter
the value: 50
Enter
the key: C++
Enter
the value: 67
Enter
the key: Python
Enter
the value: 90
My
dictionary is: {'DBMS': '50', 'C++': '67', 'Python': '90'}
The
for loop is used to take user input for dictionary. The number of key value
pair will be accepted by compiler as per the user input you have stored in n.
In above example user input for key value pair is 3 so total 3 key value pairs
will be accepted by compiler.
0 टिप्पण्या
कृपया तुमच्या प्रियजनांना लेख शेअर करा आणि तुमचा अभिप्राय जरूर नोंदवा. 🙏 🙏