Python:使用*args作为字典键
我正在尝试找出如何获取字典列表:Python:使用*args作为字典键,python,dictionary,Python,Dictionary,我正在尝试找出如何获取字典列表: some_list = [{'a':1, 'b':{'c':2}}, {'a':3, 'b':{'c':4}}, {'a':5, 'b':{'c':6}}] 然后使用键的参数获取这种情况下的嵌套值c。有什么想法吗?我试着做一些事情,比如: def compare_something(comparison_list, *args): new_list = [] for something in comparison_list:
some_list = [{'a':1, 'b':{'c':2}}, {'a':3, 'b':{'c':4}}, {'a':5, 'b':{'c':6}}]
然后使用键的参数获取这种情况下的嵌套值c
。有什么想法吗?我试着做一些事情,比如:
def compare_something(comparison_list, *args):
new_list = []
for something in comparison_list:
company_list.append(company[arg1?][arg2?])
return new_list
compare_something(some_list, 'b', 'c')
但我不太确定如何指定我想要的参数的具体顺序,在这里我需要它们。有什么想法吗?如果您确定列表中的每个项目实际上都有必要的嵌套字典
for val in comparison_list:
for a in args:
val = val[a]
# Do something with val
在中迭代完成的重复解包/导航也可以通过递归完成:
some_list = [{'a':1, 'b':{'c':2}}, {'a':3, 'b':{'c':4}}, {'a':5, 'b':{'c':6}}]
def extract(nested_dictionary, *keys):
"""
return the object found by navigating the nested_dictionary along the keys
"""
if keys:
# There are keys left to process.
# Unpack one level by navigating to the first remaining key:
unpacked_value = nested_dictionary[keys[0]]
# The rest of the keys won't be handled in this recursion.
unprocessed_keys = keys[1:] # Might be empty, we don't care here.
# Handle yet unprocessed keys in the next recursion:
return extract(unpacked_value, *unprocessed_keys)
else:
# There are no keys left to process. Return the input object (of this recursion) as-is.
return nested_dictionary # Might or might not be a dict at this point, so disregard the name.
def compare_something(comparison_list, *keys):
"""
for each nested dictionary in comparison_list, return the object
found by navigating the nested_dictionary along the keys
I'm not really sure what this has to do with comparisons.
"""
return [extract(d, *keys) for d in comparison_list]
compare_something(some_list, 'b', 'c') # returns [2, 4, 6]
你的预期结果是什么?什么是公司名单,在你的职能范围内新的名单在哪里变化,什么是公司?现在你总是返回一个空列表,还是我遗漏了什么?应该是
new\u list.append(
谢谢你尝试只返回嵌套CY的值你也可以遍历嵌套DICT——不过,它的使用现在有点不受欢迎了。。。