问题:通过索引访问Python字典的元素

考虑一个像

mydict = {
  'Apple': {'American':'16', 'Mexican':10, 'Chinese':5},
  'Grapes':{'Arabian':'25','Indian':'20'} }

例如,如何访问该词典的特定元素?例如,我想在对Apple的第一个元素进行某种格式设置后再打印第一个元素,在我们的例子中,该格式仅是“ American”?

附加信息上面的数据结构是通过在python函数中解析输入文件创建的。一旦创建,它在该运行中将保持不变。

我在函数中使用此数据结构。

因此,如果文件发生更改,则下次运行此应用程序时,文件的内容将有所不同,因此此数据结构的内容将有所不同,但格式将相同。因此,您在我的职能中看到我,我不知道Apple中的第一个元素是“ American”或其他任何元素,因此我不能直接使用“ American”作为键。

Consider a dict like

mydict = {
  'Apple': {'American':'16', 'Mexican':10, 'Chinese':5},
  'Grapes':{'Arabian':'25','Indian':'20'} }

How do I access for instance a particular element of this dictionary? for instance, I would like to print the first element after some formatting the first element of Apple which in our case is ‘American’ only?

Additional information The above data structure was created by parsing an input file in a python function. Once created however it remains the same for that run.

I am using this data structure in my function.

So if the file changes, the next time this application is run the contents of the file are different and hence the contents of this data structure will be different but the format would be the same. So you see I in my function I don’t know that the first element in Apple is ‘American’ or anything else so I can’t directly use ‘American’ as a key.


回答 0

鉴于它是字典,您可以使用键来访问它。获取存储在“ Apple”下的词典,请执行以下操作:

>>> mydict["Apple"]
{'American': '16', 'Mexican': 10, 'Chinese': 5}

并让其中有多少是美国人(16),请执行以下操作:

>>> mydict["Apple"]["American"]
'16'

Given that it is a dictionary you access it by using the keys. Getting the dictionary stored under “Apple”, do the following:

>>> mydict["Apple"]
{'American': '16', 'Mexican': 10, 'Chinese': 5}

And getting how many of them are American (16), do like this:

>>> mydict["Apple"]["American"]
'16'

回答 1

如果问题是,如果我知道我有一个包含“ Apple”作为水果和“ American”作为一种苹果的字典,我将使用:

myDict = {'Apple': {'American':'16', 'Mexican':10, 'Chinese':5},
          'Grapes':{'Arabian':'25','Indian':'20'} }


print myDict['Apple']['American']

正如其他人建议的那样。如果问题是,则当您将任意文件读入dict数据结构的dict中时,您不知道是否存在“ Apple”作为水果,是否存在“ American”作为“ Apple”类型,您可以执行以下操作:

print [ftype['American'] for f,ftype in myDict.iteritems() if f == 'Apple' and 'American' in ftype]

还是更好,所以如果您知道只有Apple拥有American类型,就不必不必要地遍历整个dict。

if 'Apple' in myDict:
    if 'American' in myDict['Apple']:
        print myDict['Apple']['American']

在所有这些情况下,字典实际存储条目的顺序都无关紧要。如果您确实担心订单,则可以考虑使用OrderedDict

http://docs.python.org/dev/library/collections.html#collections.OrderedDict

If the questions is, if I know that I have a dict of dicts that contains ‘Apple’ as a fruit and ‘American’ as a type of apple, I would use:

myDict = {'Apple': {'American':'16', 'Mexican':10, 'Chinese':5},
          'Grapes':{'Arabian':'25','Indian':'20'} }


print myDict['Apple']['American']

as others suggested. If instead the questions is, you don’t know whether ‘Apple’ as a fruit and ‘American’ as a type of ‘Apple’ exist when you read an arbitrary file into your dict of dict data structure, you could do something like:

print [ftype['American'] for f,ftype in myDict.iteritems() if f == 'Apple' and 'American' in ftype]

or better yet so you don’t unnecessarily iterate over the entire dict of dicts if you know that only Apple has the type American:

if 'Apple' in myDict:
    if 'American' in myDict['Apple']:
        print myDict['Apple']['American']

In all of these cases it doesn’t matter what order the dictionaries actually store the entries. If you are really concerned about the order, then you might consider using an OrderedDict:

http://docs.python.org/dev/library/collections.html#collections.OrderedDict


回答 2

正如我注意到您的描述一样,您只知道解析器将为您提供一个字典,其值也就是字典,如下所示:

sampleDict = {
              "key1": {"key10": "value10", "key11": "value11"},
              "key2": {"key20": "value20", "key21": "value21"}
              }

因此,您必须迭代父词典。如果要打印或访问sampleDict.values()列表中的所有第一个词典键,则可以使用以下方法:

for key, value in sampleDict.items():
    print value.keys()[0]

如果您只想访问中第一个项目的第一个键sampleDict.values(),这可能会很有用:

print sampleDict.values()[0].keys()[0]

如果使用您在问题中给出的示例,我的意思是:

sampleDict = {
              'Apple': {'American':'16', 'Mexican':10, 'Chinese':5},
              'Grapes':{'Arabian':'25','Indian':'20'}
              }

第一个代码的输出是:

American
Indian

第二个代码的输出是:

American

As I noticed your description, you just know that your parser will give you a dictionary that its values are dictionary too like this:

sampleDict = {
              "key1": {"key10": "value10", "key11": "value11"},
              "key2": {"key20": "value20", "key21": "value21"}
              }

So you have to iterate over your parent dictionary. If you want to print out or access all first dictionary keys in sampleDict.values() list, you may use something like this:

for key, value in sampleDict.items():
    print value.keys()[0]

If you want to just access first key of the first item in sampleDict.values(), this may be useful:

print sampleDict.values()[0].keys()[0]

If you use the example you gave in the question, I mean:

sampleDict = {
              'Apple': {'American':'16', 'Mexican':10, 'Chinese':5},
              'Grapes':{'Arabian':'25','Indian':'20'}
              }

The output for the first code is:

American
Indian

And the output for the second code is:

American

EDIT 1:

Above code examples does not work for version 3 and above of python; since from version 3, python changed the type of output of methods keys and values from list to dict_values. Type dict_values is not accepting indexing, but it is iterable. So you need to change above codes as below:

First One:

for key, value in sampleDict.items():
    print(list(value.keys())[0])

Second One:

print(list(list(sampleDict.values())[0].keys())[0])

回答 3

作为奖励,我想为您的问题提供一种不同的解决方案。您似乎正在处理嵌套字典,这通常很乏味,尤其是当您必须检查内部键的存在时。

在pypi上有一些与此有关的有趣库,这是您的快速搜索

在您的特定情况下,dict_digger似乎很合适。

>>> import dict_digger
>>> d = {
  'Apple': {'American':'16', 'Mexican':10, 'Chinese':5},
  'Grapes':{'Arabian':'25','Indian':'20'} 
}

>>> print(dict_digger.dig(d, 'Apple','American'))
16
>>> print(dict_digger.dig(d, 'Grapes','American'))
None

As a bonus, I’d like to offer kind of a different solution to your issue. You seem to be dealing with nested dictionaries, which is usually tedious, especially when you have to check for existence of an inner key.

There are some interesting libraries regarding this on pypi, here is a quick search for you.

In your specific case, dict_digger seems suited.

>>> import dict_digger
>>> d = {
  'Apple': {'American':'16', 'Mexican':10, 'Chinese':5},
  'Grapes':{'Arabian':'25','Indian':'20'} 
}

>>> print(dict_digger.dig(d, 'Apple','American'))
16
>>> print(dict_digger.dig(d, 'Grapes','American'))
None

回答 4

您可以使用dict['Apple'].keys()[0]获取Apple字典中的第一个键,但是不能保证它会是American。词典中键的顺序可以根据词典的内容和键的添加顺序而变化。

You can use dict['Apple'].keys()[0] to get the first key in the Apple dictionary, but there’s no guarantee that it will be American. The order of keys in a dictionary can change depending on the contents of the dictionary and the order the keys were added.


回答 5

我知道这是8岁,但似乎没有人真正阅读并回答过这个问题。

您可以在字典上调用.values()以获得内部字典的列表,从而按索引访问它们。

>>> mydict = {
...  'Apple': {'American':'16', 'Mexican':10, 'Chinese':5},
...  'Grapes':{'Arabian':'25','Indian':'20'} }

>>>mylist = list(mydict.values())
>>>mylist[0]
{'American':'16', 'Mexican':10, 'Chinese':5},
>>>mylist[1]
{'Arabian':'25','Indian':'20'}

>>>myInnerList1 = list(mylist[0].values())
>>>myInnerList1
['16', 10, 5]
>>>myInnerList2 = list(mylist[1].values())
>>>myInnerList2
['25', '20']

I know this is 8 years old, but no one seems to have actually read and answered the question.

You can call .values() on a dict to get a list of the inner dicts and thus access them by index.

>>> mydict = {
...  'Apple': {'American':'16', 'Mexican':10, 'Chinese':5},
...  'Grapes':{'Arabian':'25','Indian':'20'} }

>>>mylist = list(mydict.values())
>>>mylist[0]
{'American':'16', 'Mexican':10, 'Chinese':5},
>>>mylist[1]
{'Arabian':'25','Indian':'20'}

>>>myInnerList1 = list(mylist[0].values())
>>>myInnerList1
['16', 10, 5]
>>>myInnerList2 = list(mylist[1].values())
>>>myInnerList2
['25', '20']

回答 6

您不能依赖字典的顺序。但是您可以尝试以下方法:

dict['Apple'].items()[0][0]

如果您希望保留订单,则可以使用以下网址http : //www.python.org/dev/peps/pep-0372/#ordered-dict-api

You can’t rely on order on dictionaries. But you may try this:

dict['Apple'].items()[0][0]

If you want the order to be preserved you may want to use this: http://www.python.org/dev/peps/pep-0372/#ordered-dict-api


回答 7

简单示例以了解如何访问字典中的元素:-

创建字典

d = {'dog' : 'bark', 'cat' : 'meow' } 
print(d.get('cat'))
print(d.get('lion'))
print(d.get('lion', 'Not in the dictionary'))
print(d.get('lion', 'NA'))
print(d.get('dog', 'NA'))

探索有关Python词典的更多信息,并在此处进行交互学习…

Simple Example to understand how to access elements in the dictionary:-

Create a Dictionary

d = {'dog' : 'bark', 'cat' : 'meow' } 
print(d.get('cat'))
print(d.get('lion'))
print(d.get('lion', 'Not in the dictionary'))
print(d.get('lion', 'NA'))
print(d.get('dog', 'NA'))

Explore more about Python Dictionaries and learn interactively here…


回答 8

尽管有很多问题的答案,但很少有人指出字典是无序的映射,因此(直到使用Python 3.7祝福插入顺序)字典中“第一个”条目的想法实际上是没道理 甚至OrderedDict只能通过使用诸如以下的丑陋的数字索引来访问mydict[mydict.keys()[0]](仅Python 2,因为在Python 3中keys()是不可下标的迭代器。)

从3.7开始,并在3,6中付诸实践-引入了新的行为,但直到3.7才包含在语言规范中-在字典的键,值或项上进行迭代(我相信,也设置)将首先产生最近插入的对象。仍然没有简单的方法可以通过数字插入索引来访问它们。

关于选择和“格式化”项目的问题,如果您知道要在字典中检索的键,通常可以将该键用作下标来检索它(my_var = mydict['Apple'])。

如果您确实希望能够通过条目号为项目建立索引(而忽略了特定条目号会随着插入而改变的事实),那么适当的结构可能就是一个由两个元素组成的元组的列表。代替

mydict = {
  'Apple': {'American':'16', 'Mexican':10, 'Chinese':5},
  'Grapes':{'Arabian':'25','Indian':'20'} }

您可以使用:

mylist = [
    ('Apple', {'American':'16', 'Mexican':10, 'Chinese':5}),
    ('Grapes', {'Arabian': '25', 'Indian': '20'}
]

在这种情况下,第一个条目采用mylist[0]经典的列表扩展名形式,其值为('Apple', {'American':'16', 'Mexican':10, 'Chinese':5})。您可以如下遍历整个列表:

for (key, value) in mylist:  # unpacks to avoid tuple indexing
    if key == 'Apple':
        if 'American' in value:
            print(value['American'])

但是,如果您知道要查找键“ Apple”,那么为什么不使用字典呢?

您可以通过缓存键列表来引入更高级别的间接访问,但是保持两个数据结构同步的复杂性将不可避免地增加代码的复杂性。

Few people appear, despite the many answers to this question, to have pointed out that dictionaries are un-ordered mappings, and so (until the blessing of insertion order with Python 3.7) the idea of the “first” entry in a dictionary literally made no sense. And even an OrderedDict can only be accessed by numerical index using such uglinesses as mydict[mydict.keys()[0]] (Python 2 only, since in Python 3 keys() is a non-subscriptable iterator.)

From 3.7 onwards and in practice in 3,6 as well – the new behaviour was introduced then, but not included as part of the language specification until 3.7 – iteration over the keys, values or items of a dict (and, I believe, a set also) will yield the least-recently inserted objects first. There is still no simple way to access them by numerical index of insertion.

As to the question of selecting and “formatting” items, if you know the key you want to retrieve in the dictionary you would normally use the key as a subscript to retrieve it (my_var = mydict['Apple']).

If you really do want to be able to index the items by entry number (ignoring the fact that a particular entry’s number will change as insertions are made) then the appropriate structure would probably be a list of two-element tuples. Instead of

mydict = {
  'Apple': {'American':'16', 'Mexican':10, 'Chinese':5},
  'Grapes':{'Arabian':'25','Indian':'20'} }

you might use:

mylist = [
    ('Apple', {'American':'16', 'Mexican':10, 'Chinese':5}),
    ('Grapes', {'Arabian': '25', 'Indian': '20'}
]

Under this regime the first entry is mylist[0] in classic list-endexed form, and its value is ('Apple', {'American':'16', 'Mexican':10, 'Chinese':5}). You could iterate over the whole list as follows:

for (key, value) in mylist:  # unpacks to avoid tuple indexing
    if key == 'Apple':
        if 'American' in value:
            print(value['American'])

but if you know you are looking for the key “Apple”, why wouldn’t you just use a dict instead?

You could introduce an additional level of indirection by cacheing the list of keys, but the complexities of keeping two data structures in synchronisation would inevitably add to the complexity of your code.


回答 9

使用以下小功能,挖掘树形字典变得非常容易:

def dig(tree, path):
    for key in path.split("."):
        if isinstance(tree, dict) and tree.get(key):
            tree = tree[key]
        else:
            return None
    return tree

现在,dig(mydict, "Apple.Mexican")返回10,而dig(mydict, "Grape")产生子树{'Arabian':'25','Indian':'20'}。如果字典中不包含键,则dig返回None

请注意,您可以轻松地从’。’更改(甚至参数化)分隔符char。到“ /”,“ |” 等等

With the following small function, digging into a tree-shaped dictionary becomes quite easy:

def dig(tree, path):
    for key in path.split("."):
        if isinstance(tree, dict) and tree.get(key):
            tree = tree[key]
        else:
            return None
    return tree

Now, dig(mydict, "Apple.Mexican") returns 10, while dig(mydict, "Grape") yields the subtree {'Arabian':'25','Indian':'20'}. If a key is not contained in the dictionary, dig returns None.

Note that you can easily change (or even parameterize) the separator char from ‘.’ to ‘/’, ‘|’ etc.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。