Tuple and Dictionaries
Tuple:
=========
>A tuple is a Python sequence which stores a group of elements or items.
>Main difference between tuple and list is, Tuples are immutable but list are mutable.
Hence we can not perform operations like append(),extend(),insert(),remove(),pop()
and clear() on tuples.
Creating Tuples :
---------------
1. creating empty tuple
>>> tup1 = ()
>>> type(tup1)
<class 'tuple'>
2. if single element by default will take integer so to make it tuple then it should be ended with ,
>>> tup1 = (10)
>>> type(tup1)
<class 'int'>
>>> tup1 = (10,)
>>> type(tup1)
<class 'tuple'>
>>>
3. type casting
>>> tup1 = [10,20,30]
>>> type(tup1)
<class 'list'>
>>> tup2 = tuple(tup1)
>>> type(tup2)
<class 'tuple'>
4. using range function
>>> a = tuple(range(1,10,2))
>>> a
(1, 3, 5, 7, 9)
Accessing Tuple elements:
========================
tup = (50,60,70,80,90,100)
>>> tup = (50,60,70,80,90,100)
>>> print(tup[0])
50
>>> print(tup[5])
100
>>> print(tup[-1])
100
>>> print(tup[-6])
50
>>> print(tup[:])
(50, 60, 70, 80, 90, 100)
>>> print(tup[1:4])
(60, 70, 80)
>>> print(tup[::2])
(50, 70, 90)
>>> print(tup[::-2])
(100, 80, 60)
>>> print(tup[::-1])
(100, 90, 80, 70, 60, 50)
>>> print(tup[-4:-1])
(70, 80, 90)
>>> student = (10,'srinivas',50,60,65,61,70)
>>> student
(10, 'srinivas', 50, 60, 65, 61, 70)
>>> rno,name = student[0:2]
>>> rno
10
>>> name
'srinivas'
>>> marks = student[2:7]
>>> type(marks)
<class 'tuple'>
>>> for i in marks:
print(i)
50
60
65
61
70
Basic operations on Tuples :
-----------------------------
1. Finding length
2. Concatenation
3. repetition
4. membership
>>> student = (10,'srinivas',50,60,65,61,70)
>>> len(student)
7
>>> fees = (25000.00,)*4
>>> fees
(25000.0, 25000.0, 25000.0, 25000.0)
>>> type(fees)
<class 'tuple'>
>>> student1 = student + fees
>>> student1
(10, 'srinivas', 50, 60, 65, 61, 70, 25000.0, 25000.0, 25000.0, 25000.0)
>>> name = 'srinivas'
>>> name in student1
True
>>> name not in student1
False
>>> tpl = (10,11,12)
>>> tpl1 = tpl *3
>>> tpl1
(10, 11, 12, 10, 11, 12, 10, 11, 12)
Functions to process Tuples :
============================
>>> tpl = (1,3,2,4,13,23,22,19,2,13,22,5)
>>> len(tpl)
12
>>> min(tpl)
1
>>> max(tpl)
23
>>> tpl.count(2)
2
>>> tpl.index(2)
2
>>> sorted(tpl)
[1, 2, 2, 3, 4, 5, 13, 13, 19, 22, 22, 23]
>>> sorted(tpl,reverse = True)
[23, 22, 22, 19, 13, 13, 5, 4, 3, 2, 2, 1]
eval function :
==============
num = eval(input("Enter the elements in (): "))
>>> num = eval(input("Enter the elements in (): "))
Enter the elements in (): (1,2,3,4)
>>> num
(1, 2, 3, 4)
>>> num = eval(input("Enter the elements in (): "))
Enter the elements in (): [1,2,3,4]
>>> num
[1, 2, 3, 4]
>>> num = eval(input("Enter the elements in (): "))
Enter the elements in (): 12,2,3,44
>>> num
(12, 2, 3, 44)
1. Write a program to accepts elements in the form of tuple and display their sum and average.
num = eval(input("enter the elements in ():"))
s = 0
n = len(num)
for i in num:
s = s+i
print("sum is: ",s)
print("avg is: ",s/n)
2. Usage of split function
>>> num = input("Enter the elements in , separator: ")
Enter the elements in (): 1,2,3,4,5
>>> num
'1,2,3,4,5'
>>> str = num.split(',')
>>> str
['1', '2', '3', '4', '5']
>>> tup = tuple(str)
>>> tup
('1', '2', '3', '4', '5')
Nested Tuples:
===========
A tuple inserted inside another tuple is called nested tuple.
tup = (50,60,70,80,90,(200,201)) # tuple with 6 elements
>>> tup = (50,60,70,80,90,(200,201))
>>> tup[5]
(200, 201)
>>> tup[5][0]
200
>>>
Inserting elements in Tuple :
===========================
num = eval(input("enter the elements in ():"))
pos = int(input("Enter the position number to insert value:\n"))
new = int(input("enter the values to insert\n"))
temp = num[0:pos-1]
new_tup =(new,)
temp2 = num[pos-1:len(num)+1]
new_temp = temp+new_tup+temp2
print("final tuple is :\n",new_temp)
output:
-------
enter the elements in ():(10,20,30,40,50)
Enter the position number to insert value:
3
enter the values to insert
25
final tuple is :
(10, 20, 25, 30, 40, 50)
Dictionaries :
================
A Dictionary represents a group of elements arranged in the form of key-value pairs.
>>> details = {'rno':101,'name':'srinivas','sal':2000}
>>> print("Roll no is {}".format(details['rno']))
Roll no is 101
>>> print("name is : ",details['name'])
name is : srinivas
Operations on Dictionaries:
-------------------------
To access elements of dictionary , we should not use indexing and slicing.
For example dcit[0] or dict[1:3] etc. expressions will give error.
To access the value associated with a key, we can mentions the key name inside square braces.
as, dict['name']
1. Using length function
>>> details
{'rno': 101, 'name': 'srinivas', 'sal': 2000}
>>> len(details)
3
>>> details['sal']
2000
>>> details['sal'] = 4000
>>> details
{'rno': 101, 'name': 'srinivas', 'sal': 4000}
>>>
>>> details
{'rno': 101, 'name': 'srinivas', 'sal': 4000}
>>> details['location'] = 'Hyderabad' # add element
>>> details
{'rno': 101, 'name': 'srinivas', 'sal': 4000, 'location': 'Hyderabad'}
>>> del details['rno'] # remove element
>>> details
{'name': 'srinivas', 'sal': 4000, 'location': 'Hyderabad'}
>>> details
{'name': 'srinivas', 'sal': 4000, 'location': 'Hyderabad'}
>>> 'gender' in details
False
>>> 'location' in details
True
# Keys should be unique key. It means duplicate keys are not allowed.
If we enter same key again, the old key will be overwritten and only the new key will be available.
>>> details = {1:'ravi',2:'rajesh',1:'suresh'}
>>> details
{1: 'suresh', 2: 'rajesh'}
# Keys should be immutable type. we can use a number,string or tuple as keys since they are immutable.
We can not use lists or dictionaries as keys. If they used as keys, we will get 'TypeError'.
consider following example
>>> emp = {'rno':101,['name']:'srinivas'}
Traceback (most recent call last):
File "<pyshell#182>", line 1, in <module>
emp = {'rno':101,['name']:'srinivas'}
TypeError: unhashable type: 'list'
Dictionary Methods :
=====================
Various methods are provided to process the elements of a dictionary. These methods
generally retrieve or manipulate the contents of a dictionary.
>>> d = {'eid':101,'ename':'John','sal':24000}
>>> d
{'eid': 101, 'ename': 'John', 'sal': 24000}
>>> d1 = d.copy()
>>> d1
{'eid': 101, 'ename': 'John', 'sal': 24000}
>>> d.items()
dict_items([('eid', 101), ('ename', 'John'), ('sal', 24000)])
>>> d.keys()
dict_keys(['eid', 'ename', 'sal'])
>>> d.values()
dict_values([101, 'John', 24000])
1. Write a program to create dictionary and find sum of values.
>>> a = eval(input("enter elements in {}:"))
enter elements in {}:{'A':10,'B':20}
>>> a.values()
dict_values([10, 20])
>>> sum(a.values())
2. Write a program to create a dictionary from keyboard and display elements.
x = {}
n = int(input("no.of elements:"))
for i in range(n):
print('enter key: \n',end = '')
k=input()
print('enter value: \n',end = '')
v=int(input())
x.update({k:v})
print('the dictionary is :',x)
NOTE: The key-value pairs which are entered by us from key board are not displayed
in the same order. Dictionaries will not maintain orderliness of pairs.
usage of get() method:
------------------
x = {}
n = int(input("Enter no.of players:\n"))
for i in range(n):
k = input("Enter player name : \n")
v = int(input("Enter score:\n"))
x.update({k:v})
print("Team players are: \n" , x.keys())
player_name = input("Enter the player name : \n")
#get function return the value of key , if key not found then return -1
score=x.get(player_name,-1)
if (score != -1):
print('%s scored %d'%(player_name,score))
else:
print("Player not found")
4. Python program to show usage of for loop to retrieve elements of dictionary.
-
colors = {'R':'red','G':'Green','B':'Blue'}
for i in colors:
print(i)
for j in colors:
print(colors[j])
print(colors.items())
for k,v in colors.items():
print("key ={} and value = {}".format(k,v))
5. Python program find occurrences of each character in given string.
letters = {}
x = "Book"
for i in x:
letters[i] = letters.get(i,0)+1
print(letters)
for k,v in letters.items():
print(" {} is found {} times".format(k,v))
dictionary = {'key' : 'value',
'key_2': 'value_2'}
nested_dict = { 'dictA': {'key_1': 'value_1'},
'dictB': {'key_2': 'value_2'}}
How to create a nested dictionary
people = {1: {'name': 'John', 'age': '27', 'gen': 'Male'},
2: {'name': 'Marie', 'age': '22', 'gen': 'Female'}}
print(people)
Access the elements using the [] syntax
people = {1: {'name': 'John', 'age': '27', 'gen': 'Male'},
2: {'name': 'Marie', 'age': '22', 'gen': 'Female'}}
print(people[1]['name'])
print(people[1]['age'])
print(people[1]['gen'])
How to change or add elements in a nested dictionary?
people = {1: {'name': 'John', 'age': '27', 'gen': 'Male'},
2: {'name': 'Marie', 'age': '22', 'gen': 'Female'}}
people[3] = {}
people[3]['name'] = 'Luna'
people[3]['age'] = '24'
people[3]['gen'] = 'Female'
people[3]['married'] = 'No'
print(people[3])
Add another dictionary to the nested dictionary
people = {1: {'name': 'John', 'age': '27', 'gen': 'Male'},
2: {'name': 'Marie', 'age': '22', 'gen': 'Female'},
3: {'name': 'Luna', 'age': '24', 'gen': 'Female', 'married': 'No'}}
people[4] = {'name': 'Peter', 'age': '29', 'gen': 'Male', 'married': 'Yes'}
print(people[4])
How to delete elements from a nested dictionary?
people = {1: {'name': 'John', 'age': '27', 'gen': 'Male'},
2: {'name': 'Marie', 'age': '22', 'gen': 'Female'},
3: {'name': 'Luna', 'age': '24', 'gen': 'Female', 'married': 'No'},
4: {'name': 'Peter', 'age': '29', 'gen': 'Male', 'married': 'Yes'}}
del people[3]['married']
del people[4]['married']
print(people[3])
print(people[4])
How to delete dictionary from a nested dictionary?
people = {1: {'name': 'John', 'age': '27', 'gen': 'Male'},
2: {'name': 'Marie', 'age': '22', 'gen': 'Female'},
3: {'name': 'Luna', 'age': '24', 'gen': 'Female'},
4: {'name': 'Peter', 'age': '29', 'gen': 'Male'}}
del people[3], people[4]
print(people)
How to iterate through a Nested dictionary?
people = {1: {'Name': 'John', 'Age': '27', 'Sex': 'Male'},
2: {'Name': 'Marie', 'Age': '22', 'Sex': 'Female'}}
for p_id, p_info in people.items():
print("\nPerson ID:", p_id)
for key in p_info:
print(key + ':', p_info[key])
Key Points to Remember:
1.Nested dictionary is an unordered collection of dictionary
2.Slicing Nested Dictionary is not possible.
3.We can shrink or grow nested dictionary as need.
4.Like Dictionary, it also has key and value.
5.Dictionary are accessed using key.
No comments:
Post a Comment