【问题标题】:Get values by latest index of nested dictionary in Python通过Python中嵌套字典的最新索引获取值
【发布时间】:2015-03-01 18:49:47
【问题描述】:

如果我不知道所有键,如何通过嵌套字典的最新键获取值?

例如:

dict = { students: { id1: value1, id2: value2, id3: value3} , lecturers: {}}
>>> dict[id2]
value2

另外,如果我想通过只写 dict[id2] 来更改或删除 dict[students][id2]...

【问题讨论】:

  • 这里的最新是什么意思???
  • "id2" 不是main dict 的键,它是key1 dict 的键,它是main dict 的键。你声明>>> dict[id2]是错误的
  • dict 是无序的,你无法跟踪
  • 是否可以在单独的子字典中有多个 id2 值?
  • @Hackaholic:“最新的”,我认为 OP 的意思是“最深的”

标签: python dictionary nested ordereddictionary


【解决方案1】:

正如 cmets 中提到的,'dict' 是 python 中的一个特殊词,不应该作为变量名重复使用,因为它可能导致冲突和奇怪的行为。

这里还值得记住的是,python 中的字典不会(必然)保留它们的顺序。 From the docs:

最好将字典视为一组无序的键:值对,并要求键是唯一的(在一个字典中)。

您所做的是嵌套了一个字典,因此第一个字典(键:students)将返回第二个字典(带有各种 id 等)。这也值得注意,除非您在其他地方为学生分配了一个值,不能作为键使用,必须是字符串、元组或数字。

所以 - 如果你的意思是“最深”,那么你需要使用结构:

dictionary_name['top_key'] 访问嵌套字典,然后是第二个键,给你一些看起来像 dictionary_name['students']['id1'] 的东西(注意这里的键名周围的引号!)

如果您的意思是“最近添加”中的“最新”,那么您需要使用不同的结构,like OrderedDict. 我已将其拆分出来,以便您查看如何更新字典,这是后一部分问题!

from collections import OrderedDict
dictionary_name = OrderedDict()
dictionary_name.update({"student" : {} })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-27
    • 2022-10-07
    • 2012-06-09
    • 2021-05-10
    • 1970-01-01
    • 2020-10-01
    • 1970-01-01
    相关资源
    最近更新 更多