【问题标题】:Python dictionary of dictionaries get only primary keys [duplicate]字典的Python字典仅获取主键[重复]
【发布时间】:2018-03-27 15:17:43
【问题描述】:

我有一本字典,只想获取它的主键。 无法通过名称消除其他键。

这是一个示例字典:

{
'default': {
    'routes': '3',
    'paths': '3',
    'best_paths': {
        'broadcast': '3'
    },
    'backup_paths': {}
        },
'management': {
    'routes': '15',
    'paths': '15',
    'best_paths': {
        'local': '1',
        'direct': '1',
        'static': '1',
        'eigrp': '5'
    },
    'backup_paths': {}
        },
'test1': {
    'routes': '260',
    'paths': '275',
    'best_paths': {
        'local': '16',
        'direct': '16',
        'static': '1',
        'ospf': '33',
    },
    'backup_paths': {}
    },
}

键的数量可能不同。但字典的深度总是一样的。

我的预期结果会是这样的

key_list = 'default', 'management', 'test1' 

'python JSON only get keys in first level'这个问题的答案不起作用。

【问题讨论】:

  • list(your_dictionary) 会给你。这里的值也是字典并没有什么特别之处。
  • 你试过什么??
  • list(your_dict) 或 your_dict.keys() 就足够了。
  • 我尝试了 dict.keys() 并将所有键作为输出'default'、'routes'、'paths' ...
  • 刚刚尝试了 list(dict) ,它的输出是相同的 'default', 'routes', 'paths' ...

标签: python python-3.x dictionary


【解决方案1】:

Hi Keys 功能将提供所需的输出

dic={
'default': {
    'routes': '3',
    'paths': '3',
    'best_paths': {
        'broadcast': '3'
    },
    'backup_paths': {}
        },
'management': {
    'routes': '15',
    'paths': '15',
    'best_paths': {
        'local': '1',
        'direct': '1',
        'static': '1',
        'eigrp': '5'
    },
    'backup_paths': {}
        },
'test1': {
    'routes': '260',
    'paths': '275',
    'best_paths': {
        'local': '16',
        'direct': '16',
        'static': '1',
        'ospf': '33',
    },
    'backup_paths': {}
    },
}
print (dic.keys())

【讨论】:

  • 我尝试了键功能,但结果我得到了包括子键在内的所有键。
  • 您的意思是 dic.keys() 键提供所有键?什么是python版本?在 Python2.7 中,上面的代码只给出了主字典的键
  • 版本为 Python 3.6.2
  • 我在 3.6.2 中试过,效果很好。你能把代码复制粘贴到我的答案中并让我知道结果吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-02
  • 1970-01-01
  • 1970-01-01
  • 2015-10-25
  • 1970-01-01
  • 2019-02-05
相关资源
最近更新 更多