1

I wish to pair up two elements. I know this can be done by dictionary but the limitation in dictionary is that two key values cant be same.

Example:

    1 2
    1 3
    1 4
    4 5
    2 3
    3 4
    3 5
    3 6
    6 7

i want something like this:

    {1:2,1:3,1:4,4:5,2:3,3:4,3:5,3:6,6:7}

But by using dictionary the output generated is :

    {1: 4, 2: 3, 3: 6, 4: 5, 6: 7}

How can i overcome this problem?

Paolo
  • 21,270
  • 6
  • 38
  • 69
Max Daen
  • 21
  • 4
  • 1
    What's wrong with a list of tuples? Or a dictionary where the values are tuples or lists? – PM 2Ring Sep 20 '18 at 20:32
  • Perhaps you want an [implementation of a `multimap`](https://stackoverflow.com/questions/1731971/is-there-a-multimap-implementation-in-python)? – pault Sep 20 '18 at 20:33
  • Eg, `{'1': ['2', '3', '4'], '4': ['5'], '2': ['3'], '3': ['4', '5', '6'], '6': ['7']}` – PM 2Ring Sep 20 '18 at 20:35
  • So you want your output to look like a dictionary without being one? Or possibly what a set would output , you could put all those into list items and generate a set I’m assuming, there are no exact two alike correct ? @pm2ring is that possible to output that style with set? – vash_the_stampede Sep 20 '18 at 20:47
  • Like we have 'pair' in c++(stl), do we have anything similar to that in python? – Max Daen Sep 20 '18 at 20:50
  • It would help if you told us what you want to do with this data structure. And you still didn't say what's wrong with a list of tuples, or the other structures I've suggested. – PM 2Ring Sep 20 '18 at 20:52
  • i want to iterate over it find the most occurring element in it, will it be efficiently done in the list of tuples that you have generated? – Max Daen Sep 20 '18 at 20:55
  • @maxdean you want the most occurring element? If you said that to begin, you would have got immediate answers that would accomplish this – vash_the_stampede Sep 20 '18 at 21:05
  • It sounds like you want a [Counter](https://docs.python.org/3/library/collections.html#collections.Counter). – PM 2Ring Sep 20 '18 at 21:09
  • Yes i have applied counter already, but my main concern here is , do we have a parallel of pair(stl) in python ? – Max Daen Sep 20 '18 at 21:11
  • @pm2ring now that it’s rephrased it sounds like a duplicate tbh – vash_the_stampede Sep 20 '18 at 21:12
  • The natural way to store a collection of pairs in Python is to use a list of tuples, eg `[(1, 2), (1, 3), (1, 4), (4, 5), (2, 3), (3, 4), (3, 5), (3, 6), (6, 7)]`. If the first item in a pair is a value and the second is a count, we can feed that to a Counter to get the cumulative counts, resulting in `Counter({3: 15, 1: 9, 6: 7, 4: 5, 2: 3})` – PM 2Ring Sep 20 '18 at 21:15
  • I don't know C++ (although I do know C). And I don't know what you mean by "stl". – PM 2Ring Sep 20 '18 at 21:17
  • I think the list of tuples should do the trick , Thank you :') – Max Daen Sep 20 '18 at 21:18

0 Answers0