Python - change a dict

inspiredd :

I have a dictionary: {(1, 1): 4, (1, 2): 2, (1, 3): 5, (2, 2): 7, (2, 3): 1}

and I would like to keep these indexes where the pair number is the same : {1: 4, 2: 5}

Thanks in advance

Mehrdad Pedramfar :

Try this in just one line:

d = {(1, 1): 4, (1, 2): 2, (1, 3): 5, (2, 2): 7, (2, 3): 1}
new_d = {i[0]:j for i,j in d.items() if i[0]==i[1]}

The out put will be :

In [4]: new_d                                                                                                                                                                                                      
Out[4]: {1: 4, 2: 7}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=33310&siteId=1