为python中的额外参数返回字典
我有一个函数,它只从以“lv”开头的嵌套字典中返回一个特定键: 当用户在命令行中输入“myprogram.py extract cats”时,这将仅返回嵌套字典中以“lv”开头的键为python中的额外参数返回字典,python,arguments,Python,Arguments,我有一个函数,它只从以“lv”开头的嵌套字典中返回一个特定键: 当用户在命令行中输入“myprogram.py extract cats”时,这将仅返回嵌套字典中以“lv”开头的键 但是,我还希望用户通过在命令行中输入类似“myprogram.py extract cats detailed”的内容,获得嵌套在以“lv”开头的“cats”下的字典的更详细视图。如何让它在以“lv”开头的“cats”下打印出整个键、值对(即字典)?我可以把“详细”作为一个论据吗?像这样的东西怎么样: def dic
但是,我还希望用户通过在命令行中输入类似“myprogram.py extract cats detailed”的内容,获得嵌套在以“lv”开头的“cats”下的字典的更详细视图。如何让它在以“lv”开头的“cats”下打印出整个键、值对(即字典)?我可以把“详细”作为一个论据吗?像这样的东西怎么样:
def dict_key_starts_with(d, s='lv'):
"""Print keys that start with given value."""
for k, v in d.items():
try:
if k.startswith(s):
print(k)
except AttributeError:
pass
if isinstance(v, dict):
# nested dictionary, so run function again...
dict_key_starts_with(v, s)
dict_key_starts_with(
{'lv_foo': {'lv_bar': 123}, 'rex': 123}
)
results = []
for i in config_dict['animals']['cats']:
if i.startswith(ctx):
res = [i]
if detailed: desc.append(a[i])
results.append(res)
上述印刷品:
lv_foo
lv_bar
要回答您的每个问题,请执行以下操作: 我会把“详细”作为论点吗 对。函数表达式变为
def extract(ctx, cats, detailed):
其中,detailed
是一个布尔值
如何让它在以“lv”开头的“cats”下打印出整个键、值对(即字典)
大概是这样的:
def dict_key_starts_with(d, s='lv'):
"""Print keys that start with given value."""
for k, v in d.items():
try:
if k.startswith(s):
print(k)
except AttributeError:
pass
if isinstance(v, dict):
# nested dictionary, so run function again...
dict_key_starts_with(v, s)
dict_key_starts_with(
{'lv_foo': {'lv_bar': 123}, 'rex': 123}
)
results = []
for i in config_dict['animals']['cats']:
if i.startswith(ctx):
res = [i]
if detailed: desc.append(a[i])
results.append(res)
两件事:
- 您不需要
来遍历字典。在中为…创建一个简单的iteritems()
,可以为您提供键和值
- 结果现在是一个列表列表,其格式为[键,值(可选)]李>
祝你好运 听起来你有嵌套的字典,你需要对它们进行迭代。也许可以尝试一种递归解决方案,将当前代码放在一个函数中,该函数迭代字典键,并在值本身是字典时调用自己。