Search code examples
pythonlist-comprehension

Comprehension list of nested dictionary to get values but got keys


Fairly new to list comprehension and have the_list that I want to extract the keys of nested dictionary but I got the values instead. What am I missing or what am I doing wrong?

the_list = [{'size': 0, 'values': [], 'start': 0}, {'size': 2, 'values': [{'user': {'name': 'anna', 'id': 10, 'displayName': 'Anna'}, 'category': 'Secretary'}, {'user': {'name': 'bob', 'id': 11, 'displayName': 'Bobby'}, 'category': 'Manager'}], 'start': 0}, {'size': 1, 'values': [{'user': {'name': 'claire', 'id': 13, 'displayName': 'Clarissa Claire'}, 'category': 'Secretary'}], 'start': 0}]

list_comprehension = []
list_comprehension = [x for x in the_list for x in the_list[1]['values'][0]]
print(list_comprehension)

    >> ['user', 'category', 'user', 'category', 'user', 'category']

Want

list_comprehension = [[anna, Secretary], [bob, manager], [claire, Secretary]]

Solution

  • You could use this. I personnally try to avoid nested list comprehension as they are hard to read and debug.

    [[x['category'], x['user']['displayName']] for nest_list in the_list for x in nest_list["values"] ]
    

    Output:

    [['Secretary', 'Anna'], ['Manager', 'Bobby'], ['Secretary', 'Clarissa Claire']]
    

    EDIT: A version that doesn't have a nested comprehension list. When doing it I realised that there was one more level than I realised that makes this version a bit long. So in the end I'm not sure which one I would use in prod.

    result = []
    dict_list = [nest_list["values"] for nest_list in the_list]
    for elt in dict_list:
        for d in elt:
            result.append([d['category'], d['user']['displayName']])