简体   繁体   中英

Transfer a key and respective value from one dict to another

I have a main dict with a certain number of keys ei

dict1 = {NAME: John, Second_Name: Doe}

I have a series of this dicts and all of them are inside a list. Is there a way to loop through this list and create a list with dictionaries with, for example, only the key NAME and respective value? Is there a straightforward way to do this?

PS: I'm using dict1 as an example as in my program I'm working with dicts with a lot more keys.

I'd use a list comprehension:

list_of_dicts = [
    {'NAME': 'John', 'Second_Name': 'Doe'},
    {'NAME': 'Tim', 'Second_Name': 'Doh'},
    {'NAME': 'Mark', 'Second_Name': 'Dough'},
]

names_only = [{'NAME': d['NAME']} for d in list_of_dicts]

You can use a list comprehension :

[{'NAME': d['NAME']} for d in dictionaries]

That will raise a KeyError if NAME is not found. You can use a default instead like this:

[{'NAME': d.get('NAME', 'unknown')} for d in dictionaries]

for each dictionary, d , in dictionaries , it creates a dictionary with a single key, NAME , that has the value of d['NAME'] .

Full disclosure: I don't really know what I'm doing.

Extending on @ForeverWintr's answer, to allow the copying of keys which don't necessarily exist, which I think OP was asking for in the comments:

list_of_dicts = [
    {'NAME': 'John', 'Second_Name': 'Doe'},
    {'NAME': 'Tim', 'Second_Name': 'Doh'},
    {'NAME': 'Mark', 'Second_Name': 'Dough', 'SECRET_HANDSHAKE': True},
]

filter = ['NAME', 'SECRET_HANDSHAKE']
names_only = [{
         k: v
         for k, v in d.items()
         if k in filter
    } for d in list_of_dicts
]

I've no idea if that k in filter thing is efficient. Maybe there's a better way. It seems like you'd want to pre-cook filter into a structure that was more efficient to search. Maybe another dict?

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