1
\$\begingroup\$

I have a dictionary that looks like this:

Counter({(1, 9): 3, (4, 2): 2, (3, 0): 1, (5, 4): 1})

I would like to convert it to an array that would look like this:

[[1, 9, 3], [4, 2, 2], [3, 0, 1], [5, 4, 1]]

Help appreciated!

import itertools
import collections
import numpy as np

a = [1,5,1,1,3,4,4] # First column
b = [9,4,9,9,0,2,2] # Second column
ind = np.lexsort((b,a)) # Sort by a, then by b
print (ind)
c= [(a[i],b[i]) for i in ind]
d =np.array(c)

counts = collections.Counter()
list_of_items = d
for sublist in list_of_items:
    counts.update(itertools.combinations(sublist, 2))
\$\endgroup\$
3
  • 1
    \$\begingroup\$ Welcome to Code Review! The code you posted doesn't appear to implement the functionality that you discuss in your title and post. Are you asking how to perform this conversion? If so, this question is off-topic on Code Review and should be directed to StackOverflow instead. \$\endgroup\$ Mar 19, 2020 at 1:06
  • \$\begingroup\$ You can implement this in one line: [[*key, value] for key, value in counts.items()]. But as others have mentioned, Code Review is meant for reviewing working code, not asking for solutions. \$\endgroup\$
    – Yizhe Sun
    Mar 19, 2020 at 2:53
  • \$\begingroup\$ Thanks for solution! I am new to this so apologize for posting in wrong forum. \$\endgroup\$ Mar 19, 2020 at 5:59

0

Browse other questions tagged or ask your own question.