Home > Back-end >  How can I merge nested lists to output the key once and all values with that key "below"?
How can I merge nested lists to output the key once and all values with that key "below"?

Time:06-30

thing = [{item, abc}, {item, def}, {item, ghi}, {item2, jkl}, {item2, mno}, {item2, pqr}, ...]

to output: item abc def ghi ... item2 jkl mno ...

I've seen similar questions but none that would help me. I appreciate any help I can get!

CodePudding user response:

A solution like this could work:

thing = [{"item", "abc"}, {"item", "def"}, {"item", "ghi"}, {"item2", "jkl"}, {"item2", "mno"}, {"item2", "pqr"}]

newDict = {}
count = 0
key = ""
for s in thing:
  count = 0
  for e in s:
    if count == 0:
      if not(e in newDict):
        newDict[e] = []
      key = e
    else:
      newDict[key].append(e)
    count  = 1

print(newDict)

Output:

{'item': ['abc', 'def', 'ghi'], 'item2': ['jkl', 'mno', 'pqr']}

Since you are using a list of sets, the solution is a bit more difficult than if you used a list of lists, since sets are unindexed.

However, we can still access the elements we order them in by iterating through them.

First, we create our newDict, a dictionary will store our output. For every set, s, in thing, we will iterate through every element, e, in s.

If we are currently iterating the first element, where count = 0, if e (which can be only either "item" or "item2"), is not a key in newDict, we will create a new key with an empty list as its value. Then, we will set our variable key equal to e, so that in the next iteration, we can append the value to that dictionary.

Solution if thing is a list of lists:

thing = [["item", "abc"], ["item", "def"], ["item", "ghi"],["item2", "jkl"], ["item2", "mno"], ["item2", "pqr"]]

newDict = {}
for s in thing:
  if not(s[0] in newDict):
    newDict[s[0]] = []
  newDict[s[0]].append(s[1])

print(newDict)

I hope this made sense! Please let me know if you have any further questions or clarifications :)

  • Related