简体   繁体   中英

What is the pythonic way to extract values from dict

What is the best way to extract values from dictionary. Let's suppose we have a list of dicts:

projects = [{'project': 'project_name1', 
             'dst-repo': 'some_dst_path', 
             'src-repo': 'some_src_path', 
             'branches': ['*']},
            {...}, 
            {...}]

Now I just iterate through this dictionary and get values, something like:

   for project in projects:
       project_name = project.get('project')
       project_src = ....
       project_dst = ....
       ....
       ....

So the question is: "Are there any more pythonic approaches to extract values by key from dictionary that allow not making so many lines of code for new variable assignment?"

There's nothing wrong with what you're doing, but you can make it more compact by using a list comprehension to extract the values from the current dictionary. Eg,

projects = [
    {
        'project': 'project_name1', 
        'dst-repo': 'some_dst_path', 
        'src-repo': 'some_src_path', 
        'branches': ['*']
    },
]

keys = ['project', 'src-repo', 'dst-repo', 'branches']
for project in projects:
    name, src, dst, branches = [project[k] for k in keys]
    # Do stuff with the values
    print(name, src, dst, branches)

output

project_name1 some_src_path some_dst_path ['*']

However, this approach gets unwieldy if the number of keys is large.


If keys are sometimes absent from the dict, then you will need to use the .get method, which returns None for missing keys (unless you pass it a default arg):

name, src, dst, branches = [project.get(k) for k in keys]

If you need specific default for each key, you could put them into a dict, eg

defaults = {
    'project': 'NONAME',
    'src-repo': 'NOSRC',
    'dst-repo': 'NODEST',
    'branches': ['*'],
}

projects = [
    {
        'project': 'project_name1', 
        'src-repo': 'some_src_path', 
    },
]

keys = ['project', 'src-repo', 'dst-repo', 'branches']
for project in projects:
    name, src, dst, branches = [project.get(k, defaults[k]) for k in keys]
    # Do stuff with the values
    print(name, src, dst, branches)

output

project_name1 some_src_path NODEST ['*']
out = [elt.values() for elt in projects]
   for project in projects:
       project_name = project['project']
       project_src = ....
       project_dst = ....
       ....
       ....

I'm not sure you can get less typing

//EDIT: Ok, it looks I misunderstood the question: Assume we have a list of dicts like this:

projects = [ {'project': "proj1", 'other': "value1", 'other2': "value2"},
             {'project': "proj2", 'other': "value3", 'other2': "value4"},
             {'project': "proj2", 'other': "value3", 'other2': "value4"} ]

To extract the list of project fields, you can use the following expression:

projects_names =  [x['project'] for x in projects]

This will iterate over project list, extracting the value of 'project' key from each dictionary.

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