DEV
DEV

Reputation: 31

Removing keys from a list of dicts

I have a list:

[{'key':'key1', 'version':'1'}, {'key':'key2', 'version':'2'}, {'key':'key3', 'version':'3'}]

I want to remove all other keys from the dictionaries in the list and only to have 'key' and its value so the list would look like this:

[{'key': 'key1'}, {'key': 'key2'}, {'key': 'key3'}]

How can I extract it?

Upvotes: 1

Views: 1059

Answers (4)

user15801675
user15801675

Reputation:

You can try this:

l1 = [{'key':'key1','version':'1'},{'key':'key2','version':'2'},{'key':'key3','version':'3'}]

li2 = [{'key': j[x]} for j in l1 for x in j if x=='key']
print(li2)

Upvotes: 0

PCM
PCM

Reputation: 3021

Here is an easy solution. This uses the .pop() method to remove the key that you do not want. -

lst = [{'key':'key1','version':'1'},{'key':'key2','version':'2'},{'key':'key3','version':'3'}]

for dicts in lst:
    dicts.pop('version')

print(lst)

Result:

[{'key': 'key1'}, {'key': 'key2'}, {'key': 'key3'}]

This removes all version keys. Or you could use this method to remove everything except desired key:

new_l = []
for d in lst:
    for key in d:
        if key == 'key':
            new_l.append({key: d[key]})
print(new_l)

Or even simpler, you can use a list and dictionary comprehension to solve this. I recommend you to do this because it is more readable and efficient.:

new_l = [{key: d[key] for key in d if key == 'key'} for d in lst]
print(new_l)

Upvotes: 3

mgaliazzi
mgaliazzi

Reputation: 34

Try this:

lst = [{'key':'key1','version':'1'},{'key':'key2','version':'2'},{'key':'key3','version':'3'}]

[item.pop('version') for item in lst]

Or, removing all possible keys that does not match 'key':

lst = [{'key':'key1','version':'1'},{'key':'key2','version':'2'},{'key':'key3','version':'3'}]
for item in lst:
    for key in list(item.keys()):
        item.pop(key) if key!='key' else None

Upvotes: 0

Vincent55
Vincent55

Reputation: 33

You can try this in just one line!

yourList = [{'key':'key1','version':'1'},{'key':'key2','version':'2'},{'key':'key3','version':'3'}]
resultList = [{'key':dic['key']} for dic in yourList if 'key' in dic]
print(resultList)

Upvotes: 0

Related Questions