Description: We will use setdefault() method and dict() method to solve this problem,Firstly let's know what is setdefault() methods and what does it do .
setdefault() methods returns the value of the key(if the key is in dictionary).If not, it inserts the key with a value to dictionary.
Syntax :
dict.setdefault(key[,default_value])
key - key to be searched in the dictionary
default_value (optional) - key with a value default_value is inserted to the dictionary if key is not in the dictionary.
If not provided, the default_value will be None.
dict() method creates a dictionary.
Syntax- dict(keyword arguments )
Example: dict(name="Khushi",age=19,country="India")
Now we will use these two methods to solve the problem.
1st method by using setdefault():
So the idea to use setdefault is to convert the first parameter to key and second to the value of the dictionary and will add into the dictionary if key is not there.
Program:
tup=(['harry',20],['johny',35],['peter',20],['khushi',19])
dic={}
for a,b in tup:
dic.setdefault(a,[]).append(b)
print("Dictionary is :",dic)
Output:
Dictionary is : {'harry': [20], 'johny': [35], 'peter': [20], 'khushi': [19]}
2nd method using dict()
Its very simple to convert list of tuples into dictionary using dict() method.
Program:
tup=(['harry',20],['johny',35],['peter',20],['khushi',19])
dic=dict(tup)
print("Dictionary is :",dic)
Output:
Dictionary is : {'harry': [20], 'johny': [35], 'peter': [20], 'khushi': [19]}
Comments