Concatenating dictionary values and keys, and further operations

Roberto Bonvallet rbonvall at gmail.com
Wed Jun 7 12:22:56 EDT 2006


Girish said, through Gerard's forwarded message:
> >Thanks a lot Gerard and Roberto.but i think i should explain the exact
> >thing with an example.
> >Roberto what i have right now is concatenating the keys and the
> >corresponding values:
> >e.g {'a':[1,2],'b':[3,4,5],'c':[6,7]}  should give me
> >{'ab':[1,2][3,4,5] 'ac':[1,2][6,7] 'bc':[3,4,5][6,7]}
> >The order doesnt matter here.It could be 'ac' followed by 'bc' and 'ac'.
> >Also order doesnt matter in a string:the pair 'ab':[1,2][3,4,5] is same as
> >'ba':[3,4,5][1,2].
> >This representation means 'a' corresponds to the list [1,2] and 'b'
> >corresponds to the list [3,4,5].

The problem if that the two lists aren't distinguishable when
concatenated, so what you get is [1, 2, 3, 4, 5].  You have to pack
both lists in a tuple: {'ab': ([1, 2], [3, 4, 5]), ...}

>>> d = {'a':[1, 2], 'b':[3, 4, 5], 'c':[6, 7]}
>>> d2 = dict(((i + j), (d[i], d[j])) for i in d for j in d if i < j)
>>> d2
{'ac': ([1, 2], [6, 7]), 'ab': ([1, 2], [3, 4, 5]), 'bc': ([3, 4, 5], [6, 7])}

> >Now, for each key-value pair,e.g for 'ab' i must check each feature in the
> >list of 'a' i.e. [1,2] with each feature in list of 'b' i.e. [3,4,5].So I
> >want to take cartesian product of ONLY the 2 lists [1,2] and [3,4,5].

You can do this without creating an additional dictionary:

>>> d = {'a':[1, 2], 'b':[3, 4, 5], 'c':[6, 7]}
>>> pairs = [i + j for i in d for j in d if i < j]
>>> for i, j in pairs:
...     cartesian_product = [(x, y) for x in d[i] for y in d[j]]
...     print i + j, cartesian_product
...
ac [(1, 6), (1, 7), (2, 6), (2, 7)]
ab [(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5)]
bc [(3, 6), (3, 7), (4, 6), (4, 7), (5, 6), (5, 7)]

You can do whatever you want with this cartesian product inside the loop.

> >Finally i want to check each pair if it is present in the file,whose
> >format i had specified.

I don't understand the semantics of the file format, so I leave this
as an exercise to the reader :)
Best regards.
-- 
Roberto Bonvallet



More information about the Python-list mailing list