machin machin - 26 days ago 6
Python Question

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?"

Answer

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 ['*']
Comments