Search code examples
python-3.xlistdictionarydictionary-comprehension

How to convert a List into Dictionary in Python


How to convert list of dict to dict. Below is the list of dict.

items = [{'name': 'shirt', 'color': 'pink'},
         {'name': 'shirt', 'color': 'white'},
         {'name': 'pants', 'color': 'beige'},
         {'name': 'pants', 'color': 'black'},
         {'name': 'hat', 'color': 'beige'}]

to

items_sorted = {'shirt': ['pink', 'white'], 
                'pants': ['beige', 'black'],
                'hat': ['beige'] 
               }

I have tried:

items_sorted = {}

for item in items:
  name = item.pop('name')
  items_sorted[name] = item

But instead of appending the additional color, it would return the item with the most updated color.


Solution

  • Assuming you want to mantain duplicated values:

    items = [{'name': 'shirt', 'color': 'pink'},
             {'name': 'shirt', 'color': 'white'},
             {'name': 'pants', 'color': 'beige'},
             {'name': 'pants', 'color': 'black'},
             {'name': 'hat', 'color': 'beige'}]
    
    sorted_items = {}
    for dictionaty in items:
        if not sorted_items.get(dictionaty['name']):
            sorted_items[dictionaty['name']] = []
        sorted_items[dictionaty['name']].append(dictionaty['color'])
    

    Otherwise, use sets instead:

    sorted_items = {}
    for dictionaty in items:
        if not sorted_items.get(dictionaty['name']):
            sorted_items[dictionaty['name']] = set()
        sorted_items[dictionaty['name']].add(dictionaty['color'])
    

    and in case you want the key values to be lists, add a dictionary comprehension at the end to convert the sets into lists:

    sorted_items = {key: list(value) for key, value in sorted_items.items()}
    

    You could also use defaultdict method from the built-in collections module when initializing the "sorted_items" dictionary for simplicity (you don't need to worry about KeyErrors). Full code:

    from collections import defaultdict
    
    items = [{'name': 'shirt', 'color': 'pink'},
             {'name': 'shirt', 'color': 'white'},
             {'name': 'pants', 'color': 'beige'},
             {'name': 'pants', 'color': 'black'},
             {'name': 'hat', 'color': 'beige'}]
    
    sorted_items = defaultdict(set)
    for dictionaty in items:
        sorted_items[dictionaty['name']].add(dictionaty['color'])
    
    sorted_items = {key: list(value) for key, value in sorted_items.items()}