简体   繁体   English

从dict中提取值的pythonic方法是什么

[英]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?" 因此问题是:“是否还有更多的Python方法通过字典从键中提取值,而这些方法不允许为新变量赋值那么多行代码?”

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): 如果dict中有时缺少键,那么您将需要使用.get方法,该方法将为丢失的键返回None (除非您将默认参数传递给它):

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: 要提取project字段的列表,可以使用以下表达式:

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

This will iterate over project list, extracting the value of 'project' key from each dictionary. 这将遍历项目列表,从每个字典中提取“项目”键的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM