How to delete keys dictionary in tuple using Python

Viewed 34

I have several dictionary and i want to remove several key 2 and key 4

dict_1 = {('ABD12-GOU14', '4W', 'ASS 4W LINE 4', 80): [4, 5],
('ABD13-GOU14', '10W', 'ASS 4W LINE 5', 43): [2, 5],
('ABD14-GOU14', '11W', 'ASS 4W LINE 6', 90): [3, 5]}

i want like this

dict_1 = {('ABD12-GOU14', 'ASS 4W LINE 4'): [4, 5],
('ABD13-GOU14', 'ASS 4W LINE 5'): [2, 5],
('ABD14-GOU14', 'ASS 4W LINE 6'): [3, 5]}
2 Answers

A tuple is immutable, so you need to create new ones. For example with a dict comprehension to create a new dict where each key will be the 1st and 3rd element of the old key.

{(k[0],k[2]):v for k,v in dict_1.items()}
{('ABD12-GOU14', 'ASS 4W LINE 4'): [4, 5],
 ('ABD13-GOU14', 'ASS 4W LINE 5'): [2, 5],
 ('ABD14-GOU14', 'ASS 4W LINE 6'): [3, 5]}

this program gets the key of dictionary by using for loop. Then you can see that I have created a new dictionary which take only 1st and 3rd item from the given dictionary key.

dict_1 = {('ABD12-GOU14', '4W', 'ASS 4W LINE 4', 80): [4, 5],
('ABD13-GOU14', '10W', 'ASS 4W LINE 5', 43): [2, 5],
('ABD14-GOU14', '11W', 'ASS 4W LINE 6', 90): [3, 5]}

dict_2={}
for key in dict_1:
    dict_2[(key[0],key[2])]=dict_1[key]
print(dict_2)
Related