Home > other >  How to find the same first value, different second value, in a list and append to JSON?
How to find the same first value, different second value, in a list and append to JSON?

Time:05-19

I have a list like the following:

example_list=[("apple", "garage"),("apple","floor"),("blueberry", "tree"),("banana","ladder"), ("apple", "hammer"),("banana","gloves")]

The second value in each entry (garage, floor, ladder, gloves) will never be the same, but the first value may.

I want to put this into a JSON format such that I have the following:

{"fruit":"apple",
     "objects": "garage", "floor" , "hammer"
     
    },

{"fruit":"banana",
     "objects": "ladder", "gloves"
     
    },

{"fruit":"blueberry",
     "objects": "tree"
     
    }

Does anyone have a suggestion on how to do this in Python? Any help would be greatly appreciated. Thank you!

CodePudding user response:

You can try using a dictionary from python like this.

example_list= [("apple", "garage"),("apple","floor"),("blueberry", "tree"),("banana","ladder"), ("apple", "hammer"),("banana","gloves")]

json = {}

for pair in example_list:
    if pair[0] in json:
        json[pair[0]].append(pair[1])
    else:
        json[pair[0]] = [pair[1]]
    
print(json)

CodePudding user response:

Use dict.setdefault:

>>> example_list= [("apple", "garage"),("apple","floor"),("blueberry", "tree"),("banana","ladder"), ("apple", "hammer"),("banana","gloves")]
>>> dct = {}
>>> for fruit, obj in example_list:
...     dct.setdefault(fruit, []).append(obj)
...
>>> pp(dct)
{'apple': ['garage', 'floor', 'hammer'],
 'blueberry': ['tree'],
 'banana': ['ladder', 'gloves']}
>>> lst = [{'fruit': fruit, 'objects': objects} for fruit, objects in dct.items()]
>>> pp(lst)
[{'fruit': 'apple', 'objects': ['garage', 'floor', 'hammer']},
 {'fruit': 'blueberry', 'objects': ['tree']},
 {'fruit': 'banana', 'objects': ['ladder', 'gloves']}]
  • Related