在Python中,是否可以访问字典的第n个元素?

7

我有一段代码,其中函数foo返回一个字典。

def foo():
    # do something here
    # get data from web
    return {
        "book": {ln : wd for ln, wd, _ in data["book"]},
        "note": {ln : wd for ln, wd, _ in data["note"]},
    }

def bar():
    data = foo()
    # how to access 0th element of data["book"]
    # data["book"][0] doesnt work

问题是如何访问它的第一个元素?

2
除非您使用的是Python 3.7,否则该语言不保证字典中项目的顺序。您确定要在这里使用字典吗? - Eric
2个回答

24
< p >< code >list(data.items())< /code >将给您一个列表版本的字典中所有条目的元组,形式为< code >(键,值)< /code >,您可以根据需要对其进行迭代或索引:< /p>
>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> print(list(d.items())[0])
('a', 1)

那么在你的情况下,list(data['books'].items())


-1

我认为这个方法可行,而且比其他方法简单得多:

data['book'[0]]

这个答案并没有解决问题。它访问了字典的“b”值,而不是一个数值定义的索引。 - mortom123

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接