Turning multiple dictionary values into single output

I saw similar questions/answers but didn't find an appropriate example to follow. I have a list (of a list) of dictionaries like the following:

list_of_dictionaries = [
    [{'key1': {'subkey1': 1.0},'key2': {'subkey2': 1.0},'key3': 'abc'},
     {'key1': {'subkey1': 1.1},'key2': {'subkey2': 1.1},'key3': 'def'},
     {'key1': {'subkey1': 1.2},'key2': {'subkey2': 1.2},'key3': 'ghi'},
     {'key5': 5.0, 'key6': 6.0}],
    [{'key1': {'subkey1': 2.0},'key2': {'subkey2': 2.0},'key3': 'abc'},
     {'key1': {'subkey1': 2.1},'key2': {'subkey2': 2.1},'key3': 'def'},
     {'key1': {'subkey1': 2.2},'key2': {'subkey2': 2.2},'key3': 'ghi'},
     {'key5': 7.0, 'key6': 8.0}]
]

The challenging part is I'd like to have a single output for each of the first 3 dictionaries that pairs the 4th element of each list:

#desired output
List1 - Subkey1 value: 1.0 /// Subkey2 value: 1.0 /// Key3 value: abc /// Key5 value: 5.0 /// Key6 value: 6.0
List1 - Subkey1 value: 1.1 /// Subkey2 value: 1.1 /// Key3 value: def /// Key5 value: 5.0 /// Key6 value: 6.0
List1 - Subkey1 value: 1.2 /// Subkey2 value: 1.2 /// Key3 value: ghi /// Key5 value: 5.0 /// Key6 value: 6.0
List2 - Subkey1 value: 2.0 /// Subkey2 value: 2.0 /// Key3 value: abc /// Key5 value: 7.0 /// Key6 value: 8.0
List2 - Subkey1 value: 2.1 /// Subkey2 value: 2.1 /// Key3 value: def /// Key5 value: 7.0 /// Key6 value: 8.0
List2 - Subkey1 value: 2.2 /// Subkey2 value: 2.2 /// Key3 value: ghi /// Key5 value: 7.0 /// Key6 value: 8.0

Tried the following which is close but I'm stumped on how to only join key5 and key6 values to each corresponding print statements:

for list_of_metrics in list_of_dictionaries:  
    for dictionary in list_of_metrics:
        if 'key1' in dictionary:
            subkey1 = dictionary['key1']['subkey1']
            print('Key1, Subkey1 value: ' + str(subkey1))
        if 'key5' in dictionary:
            key5 = dictionary['key5']
            key6 = dictionary['key6']
            print('Key5 value: ' + str(key5) + ', Key6 value: ' + str(key6))

#output
Key1, Subkey1 value: 1.0
Key1, Subkey1 value: 1.1
Key1, Subkey1 value: 1.2
Key5 value: 5.0, Key6 value: 6.0
Key1, Subkey1 value: 2.0
Key1, Subkey1 value: 2.1
Key1, Subkey1 value: 2.2
Key5 value: 7.0, Key6 value: 8.0


Read more here: https://stackoverflow.com/questions/67015308/turning-multiple-dictionary-values-into-single-output

Content Attribution

This content was originally published by bck at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: