2

I have a dict which has (sourceIP, destinationIP) as key and (number_of_packets) as value. The dict output is as follows

New dictionary contents
    Key  :     Value
('A', 'B')  :  400
('B', 'A')  :  500
('A', 'C')  :  10
('C', 'A')  :  20

I need to iterate through the keys of the dict and check if the 1st element(sourceIP) in 1st key is the 2nd element(destinationIP) in the 2nd key. If yes, then I should add the value of d[k1] and d[k2] and delete the 2nd row in dict. i.e Instead of having A --> B = 400 and B --> A = 500, I should only have A -- B = 900. Please suggest me how I should iterate through the keys of dict and in that check the elements of tuple?

Veena
  • 115
  • 1
  • 9
  • Any previous attempts? One thing you could do is creating a temporary dict with keys as 2nd elements of the tuple, and use it while iterating over elements of the original dictionary. – Maciej Gol Jun 17 '14 at 06:43
  • I'm trying to use the suggestions given in http://stackoverflow.com/questions/4878881/python-tuples-dictionaries-as-keys-select-sort But not finding a way for my requirement. I could try your suggestion. Thank you. – Veena Jun 17 '14 at 06:51

1 Answers1

1

You can try with:

c = {('A', 'B')  :  400,('B', 'A')  :  500,('A', 'C')  :  10,('C', 'A')  :20}

c = {k:((c[k] if k in c else 0) + (c[k[::-1]] if (k[::-1]) in c else 0)) for k in set(map(lambda x: tuple(sorted(x)),c.keys()))}

This last line can be condensed into:

c = {k:(c.get(k,0) + c.get(k[::-1],0)) for k in set(map(lambda x: tuple(sorted(x)),c.keys()))}

Iterates over the set of normalized keys, this normalization consist on sorting the elements of the tuple which composes each key. In each iteration, check which key permutations exist in the map adding those available.

  • This gives the exact answer needed. Thank you. I just made a change to cast the value as int(c[k]) + (int(c[(k[1],k[0])])). Otherwise it was just appending the values instead of adding. Thanks for the code. – Veena Jun 17 '14 at 07:25
  • @Veena Thank to you! I just noticed the code can be reduced a little bit more (Edited the answer) – Pablo Francisco Pérez Hidalgo Jun 17 '14 at 14:25