【问题标题】:Better method to Unpacks this Nested Dictionary?解压这个嵌套字典的更好方法?
【发布时间】:2018-08-07 06:38:58
【问题描述】:

我得到一个嵌套字典如下,它会在输入字典中的第一个键时返回第三个键

tree = {"Luke" : {"Darth Vader" : {"The Chancellor"}},
        "Neal" : {"Les" : {"Joseph"}},
        "George" : {"Fred" : {"Mickey"}},
        "Robert" : {"Tim" : {"Michael"}},
        "Juan" : {"Hunter" : {"Thompson"}}}



check_con = input("Enter your Name")
for fi_name,fi_second in tree.items():
    if check_con in fi_name:
        for fi_third,fi_fourth in fi_second.items():
            print(fi_fourth)

感觉步骤有点多,有没有其他办法呢?

注意

【问题讨论】:

  • 你的意思是如果你给“卢克”你想返回“总理”?
  • @VikasDamodar,是的
  • 使用fi_second = tree[check_con]。或者 fi_second = tree.get(check_con) 如果不能保证 check_con 存在。
  • 我使用字典使它变得简单,即使它可以使用单个元组,或者列表对我来说没问题
  • .get(key[, default]) 在这里可能会有所帮助。

标签: python python-3.x dictionary nested


【解决方案1】:

您可以使用dict.get 方法和默认值为空的dict 来获取顶级dict,然后将其值转换为iter,使用next 获取第一个值

>>> check_con = 'Neal'
>>> next(iter(tree.get(check_con, {}).values()), '')
{'Joseph'}
>>> 
>>> check_con = 'xxx'
>>> next(iter(tree.get(check_con, {}).values()), '')
''
>>> 

【讨论】:

  • iter 和 next 似乎是多余的,因为这可以通过 print((tree[check_con].keys())) 来实现,
  • @Karamzov。在 python2 中,它们是多余的。您可以改为使用 dict.keys()[0]。但是在 python3 上,它们需要从 dict.keys() 中获取第一个元素。
  • 在我的字典格式中,最后一个条目是字典键还是集合?
  • @Karamzov。字典中最里面的条目是一个集合。您可以使用type 命令进行检查。 type({"The Chancellor"}) 会给<class 'set'>
  • type({"The Chancellor"}) 和`type({"Luke"}) `,一切都显示为设置,
【解决方案2】:

您可以简单地使用try-excep 表达式来确定您的名字是否存在于字典中。如果它存在,则可以返回相应值的所有值:

def get_nested_item(tree, check_on):
    try:
        sub_dict = tree[check_on]
    except KeyError:
        print("No result")
        return
    else:
        return sub_dict.values()

另请注意,关于在字典中检查您的姓名是否存在,您在这里所指的是以下行的成员资格检查:

if check_con in fi_name:

它不会检查是否相等,但会检查 check_con 是否出现在字典键中。但是,如果这是您想要的,则必须遍历您的项目并找到预期的项目。但也请注意,这可能有多个答案,或者换句话说,可能有多个键符合您的条件,这与使用字典的整个目的相矛盾。

演示:

In [11]: get_nested_item(tree, "George")
Out[11]: dict_values([{'Mickey'}])

In [12]: get_nested_item(tree, "Luke")
Out[12]: dict_values([{'The Chancellor'}])

In [13]: get_nested_item(tree, "Sarah")
No result

【讨论】:

  • @Karamzov 你的意见是什么?
【解决方案3】:

这是一个变体,我使用next(iter(...)) 来获取dictset 的“第一个”元素(请注意,tree 中最里面的大括号是sets 而不是dicts):

def get(tree, name):

    def first(seq):
        return next(iter(seq))

    if name in tree:
        return first(first(tree[name].values()))
    else:
        return None

print(get(tree=tree, name='Juan'))  # 'Thompson'
print(get(tree=tree, name='Jan'))   # None

因为sets 和dict_values(这是dict(...).values() 返回的类型)都不可索引(没有__getitem__ 方法)我使用iter 将它们变成迭代器并使用获取第一个元素next.

【讨论】:

  • 好一个,我没有得到很好的功能部分,但它返回了结果
  • 还有什么需要解释的? first 函数?
  • ~def first(seq):~
猜你喜欢
  • 1970-01-01
  • 2018-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多