从字典中提取值的最佳方法是什么?我们假设我们有一个dicts列表:
projects = [{'project': 'project_name1',
'dst-repo': 'some_dst_path',
'src-repo': 'some_src_path',
'branches': ['*']},
{...},
{...}]
现在我只是遍历这个字典并获取值,例如:
for project in projects:
project_name = project.get('project')
project_src = ....
project_dst = ....
....
....
所以问题是:“是否还有更多的pythonic方法可以通过字典中的键提取值,这样就不会为新的变量赋值生成如此多的代码行?”
答案 0 :(得分:1)
您正在做的事情没有任何问题,但您可以通过使用列表解析从当前字典中提取值来使其更紧凑。例如,
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)
<强>输出强>
project_name1 some_src_path some_dst_path ['*']
但是,如果密钥数量很大,这种方法会变得难以处理。
如果dict中有时缺少键,那么您将需要使用.get
方法,该方法会返回None
以查找缺失的键(除非您将其传递给默认的arg):
name, src, dst, branches = [project.get(k) for k in keys]
如果您需要每个键的特定默认值,您可以将它们放入dict,例如
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)
<强>输出强>
project_name1 some_src_path NODEST ['*']
答案 1 :(得分:0)
#!/usr/bin/awk -f
function fname(file, a, n)
{
n = split(file, a, ".")
return a[1]
}
BEGIN{
FS = ";"
fn = "done_" filename
print "Question;Value;User;ID" > fn
}
{
if (NR == 1)
{
for (i = 1; i <= NF; i++)
{
headers[i] = $i
}
}
else
{
for (i = 1 ; i <= NF; i++ )
{
if (i > 1)
{
print $1 FS $i FS headers[i] FS fname(filename) >> fn
}
}
}
}
答案 2 :(得分:-3)
for project in projects:
project_name = project['project']
project_src = ....
project_dst = ....
....
....
我不确定你可以减少打字
//编辑: 好吧,看起来我误解了这个问题: 假设我们有一个像这样的词典列表:
projects = [ {'project': "proj1", 'other': "value1", 'other2': "value2"},
{'project': "proj2", 'other': "value3", 'other2': "value4"},
{'project': "proj2", 'other': "value3", 'other2': "value4"} ]
要提取project
字段列表,您可以使用以下表达式:
projects_names = [x['project'] for x in projects]
这将迭代项目列表,从每个字典中提取“项目”键的值。