Home > Enterprise >  How do I pair the output from a dictionary to print the values with same key?
How do I pair the output from a dictionary to print the values with same key?

Time:10-31

I am trying to pair the values from the output. I am trying to pair the values to the same key. The code is

    key = input("parent_id:")
    value = input("child_id:")
    myList[key] = [value]
    myList

The output is

    myList = [{'parent_id' : 123, 'child_id' : 987},
    {'parent_id' : 234, 'child_id' : 876},
    {'parent_id' : 123, 'child_id' : 765},
    {'parent_id' : 345, 'child_id' : 654},
    {'parent_id' : 345, 'child_id' : 543}]

I want the output to be:

{ 123 : [987, 765],
 234 : [876],
 345 : [654, 543] }

How do i go about it?

CodePudding user response:

You can use collections.defaultdict:

from collections import defaultdict

my_list = [{'parent_id' : 123, 'child_id' : 987},
{'parent_id' : 234, 'child_id' : 876},
{'parent_id' : 123, 'child_id' : 765},
{'parent_id' : 345, 'child_id' : 654},
{'parent_id' : 345, 'child_id' : 543}]

result = defaultdict(list)

for d in my_list:
    result[d['parent_id']].append(d['child_id'])

And it's simpler if you can blindly assume the keys and values will all be in the same order and there are always the same keys:

for key, val in map(dict.values, my_list):
    result[key].append(val)

Or you could use itertools.groupby but you need to sort the data first:

from itertools import groupby
from operator import itemgetter

get_parent = itemgetter('parent_id')
get_child = itemgetter('child_id')
sorted_list = sorted(my_list, key=get_parent)

result = {k: list(map(get_child, g)) for k, g in groupby(sorted_list, get_parent)}

Result for both:

{123: [987, 765], 234: [876], 345: [654, 543]}

CodePudding user response:

This solution should work:

myList = [{'parent_id': 123, 'child_id': 987},
          {'parent_id': 234, 'child_id': 876},
          {'parent_id': 123, 'child_id': 765},
          {'parent_id': 345, 'child_id': 654},
          {'parent_id': 345, 'child_id': 543}]

return_dict = {}

for item in myList:
    key = item.get("parent_id")
    value = item.get("child_id")
    if not return_dict.get(key):
        return_dict[key] = []
    return_dict[key].append(value)

print(return_dict)

CodePudding user response:

Maybe this is what you can try -

from collections import defaultdict
out  = defaultdict(list)

myList = [{'parent_id' : 123, 'child_id' : 987},
    {'parent_id' : 234, 'child_id' : 876},
    {'parent_id' : 123, 'child_id' : 765},
    {'parent_id' : 345, 'child_id' : 654},
    {'parent_id' : 345, 'child_id' : 543}]

for item in myList:
    #print(item)                # item is a dict. 
    #print(item.keys(), item.values())
    k = item['parent_id']
    v = item['child_id']
    
    out[k].append(v)

Running it:

print(out)       #  matching expected output
  • Related