Changing list as values in dict into normal value in dict

Viewed 49

I have a dictionary with values in list. But I want to change them from list to a normal dict value. So it's looking like this:

{1: {'A': { 1: [5], 16: [5], 17: [4],
           20: [9], 22: [5], 26: [4],
           33: [2], 34: [4], 42: [2],
           47: [4], 72: [4], 80: [2]}}}

And this is the expected output: (removing the square brackets)

{1: {'A': { 1: 5, 16: 5, 17: 4,
           20: 9, 22: 5, 26: 4,
           33: 2, 34: 4, 42: 2,
           47: 4, 72: 4, 80: 2}}}

These are like extracts from my actual data, which roughly looks like this. So there's a set of these data in each of the dicts (which is like 3*3=9 in total)

{1: {"A": {}, "B": {}, "C":{}},
 2: {"A": {}, "B": {}, "C":{}},
 3: {"A": {}, "B": {}, "C":{}}}

I see a lot other questions turning a list into a value in dict. But I'm trying to do the opposite (changing my values to normal values instead of being in a list)

Would be great if you've seen other threads with similar problems and can direct me to them.

2 Answers

You need to iterate over the inner dict, and get the index 0 in each list

# solution for your specific case
values = {1: {'A': {1: [5], 16: [5], 17: [4], 20: [9], 22: [5], 26: [4],
                    33: [2], 34: [4], 42: [2], 47: [4], 72: [4], 80: [2]}}}

values = {1: {'A': {k: v[0] for k, v in values[1]['A'].items()}}}

And the generic code for any 3-level dict

values = {
    outerKey: {
        innerKey: {k: v[0] for k, v in innerDict.items()}
        for innerKey, innerDict in outerDict.items()
    } for outerKey, outerDict in values.items()
}

Recursive solution (dct is your dictionary from the question):

def remove_lists(d):
    if isinstance(d, dict):
        return {k: remove_lists(v) for k, v in d.items()}
    elif isinstance(d, list):
        return remove_lists(d[0])
    return d


print(remove_lists(dct))

Prints:

{1: {'A': {1: 5, 16: 5, 17: 4, 20: 9, 22: 5, 26: 4, 33: 2, 34: 4, 42: 2, 47: 4, 72: 4, 80: 2}}}
Related