Search code examples
pythondictionarykey

Filter through an array of dictionaries


I have a list given to me :

NameList = [
    {"key1": a, "key2": b, "key3": c},
    {"key1": d, "key3": e, "key2": f},
    {"key3": g, "key1": h, "key2": i},
    {"key2": j, "key1": k, "key3": l},
]

I am trying to create a new array with just the values of each individual 'key3'.

I have done:

NameList = above

finalarray=[]
for item in NameList:
    for item2 in item:
          if item2[0] == 'key3':
              finalarray.append(item2[0])

I get a syntax error. when I did

for item in NameList:
    for item2 in item:
          finalarray.append[item2]

I received

finalarray = [ 'key1', 'key2', 'key3' ...]

Solution

  • There's no reason to loop through the dictionaries and test each key against "key3". You can just index for the key (assuming each dictionary has that key). This can be done in one line:

    NameList = [
        {"key1": 'a', "key2": 'b', "key3": 'c'},
        {"key1": 'd', "key3": 'e', "key2": 'f'},
        {"key3": 'g', "key1": 'h', "key2": 'i'},
        {"key2": 'j', "key1": 'k', "key3": 'l'},
    ]
    
    
    finalarray = [d['key3'] for d in NameList]
    # ['c', 'e', 'g', 'l']
    

    If it's possible the key isn't in the dictionary, you can filter this dicts out:

    finalarray = [d['key3'] for d in NameList if 'key3' in d]