简体   繁体   中英

List all keys in dictionaries which are inside a list. (Dictionary in a list)

Okay, not sure how to explain this problem but here goes.

This is my dictionary myDictionary = {'12/2019' : [{'1003' : 2}, {'1040' : 3}]}

I'm trying to list out the '1003', '1040' .

I've tried using this method:

for i in range(len(a['12/2019'])):
    print(a['12/2019'][i].keys())

It kind of works however it returns me

dict_keys(['1003'])
dict_keys(['1040'])

Is there anyway I can just get 1030 and 1040 to be isolated from the ... dict_keys([''])?

You can iterate over the values of the dictionary, and if the value is a list, iterate over the dictionaries in the list, and append all the keys to the result

myDictionary = {'12/2019' : [{'1003' : 2}, {'1040' : 3}],
                '11/2019': '1005', '10/2019': 1234,
                '09/2019': [{'1006' : 2}, {'1042' : 3}],
                '08/2019': (1,2)}

keys=[]

#Iterate over values 
for value in myDictionary.values():

    #If value is a list
    if isinstance(value, list):

        #Iterate over the list
        for d in value:

            #Add the keys to the result
            keys.extend(list(d.keys()))

print(keys)

The output will be

['1003', '1040', '1006', '1042']

You can also do this via a list-comprehension, but it's not really readable, so I would avoid against it

[key for value in myDictionary.values() if isinstance(value, list) for d in value for key in d.keys()]

Iterate over the sub-dicts in the list, grabbing the keys:

for sub_dict in a['12/2019']:
   for key, val in sub_dict.items():
        print(key)

You can use a list-comprehension:

[k for v in myDictionary.values() for x in v for k in x]

In code :

myDictionary = {'12/2019' : [{'1003' : 2}, {'1040' : 3}]}

print([k for v in myDictionary.values() for x in v for k in x])
# ['1003', '1040']

You could do this by doing something like this

data = {'12/2019' : [{'1003' : 2}, {'1040' : 3}]}
# Data is a dictionary of where each value corresponding
# to the key is a list of dictionaries.

for k, v in data.items():
    # v is a list of dictionaries
    all_keys = []
    for value in v:
        all_keys.extend(list(value.keys()))
    print (all_keys)

The result is ['1003', '1040']

This may be more than you need, but if the data you shared for the example is just a small subset of what you're really looking at, here's a recursive function that can go as deep as you want it to.

Since you seem to want to skip the keys in the outer most level, I put in a spot to allow you to skip over the keys at a given depth. You shouldn't set the level argument manually since the code will just update that for itself.

def list_keys(element, ignore_levels=[], level=1):
    """
    Recursivly list keys found in an element.

    element: item to inspect.
    ignore_levels: list of numeric levels to ignore.
    level: recursion depth level.
    """
    keys = []

    # add keys if we're not ignoring this level and set iterable to values
    if isinstance(element, dict):
        if level not in ignore_levels:
            keys.extend(element.keys())
        iterable = element.values()

    # if we hve a list or tuple, we can iterate over it
    elif isinstance(element, (list, tuple)):
        iterable = element

    # if we have a single value, it's not a key and there's nothing to iterate
    else:
        iterable = []

    # Iterate over elements and append any keys found
    for i in iterable:
        subkeys = list_keys(i, ignore_levels, level + 1)
        if subkeys:
            keys.extend(subkeys)

    return keys

d = {'12/2019': [{'1003': 2}, {'1040': 3}]}
print(list_keys(d, ignore_levels=[1]))
# ['1003', '1040']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM