Programing

색인으로 Python 사전 요소에 액세스

lottogame 2020. 8. 20. 19:27
반응형

색인으로 Python 사전 요소에 액세스


다음과 같은 사전을 고려하십시오.

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

예를 들어이 사전의 특정 요소에 어떻게 액세스합니까? 예를 들어, Apple의 첫 번째 요소를 포맷 한 후 첫 번째 요소를 인쇄하고 싶습니다.

추가 정보 위의 데이터 구조는 파이썬 함수에서 입력 파일을 구문 분석하여 생성되었습니다. 그러나 일단 생성되면 해당 실행에 대해 동일하게 유지됩니다.

내 기능에서이 데이터 구조를 사용하고 있습니다.

따라서 파일이 변경되면 다음에이 응용 프로그램을 실행할 때 파일의 내용이 다르므로이 데이터 구조의 내용은 다르지만 형식은 동일합니다. 그래서 당신은 내 기능에서 내가 애플의 첫 번째 요소가 '미국식'인지 다른 것을 알지 못하기 때문에 '미국식'을 키로 직접 사용할 수 없습니다.


사전이기 때문에 키를 사용하여 액세스합니다. "Apple"에 저장된 사전을 가져 오려면 다음을 수행하십시오.

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

그리고 그들 중 얼마나 많은 미국인이 (16)인지 다음과 같이하십시오.

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

질문이 있다면 과일로 'Apple'을 포함하고 사과 유형으로 'American'을 포함하는 사전이 있다는 것을 알고 있다면 다음을 사용합니다.

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


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

다른 사람들이 제안했듯이. 대신 질문이 있다면, dict 데이터 구조의 dict에 임의의 파일을 읽을 때 'Apple'이 과일이고 'Apple'유형 인 'American'이 존재하는지 여부를 알 수없는 경우 다음과 같이 할 수 있습니다.

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


내가 당신의 설명을 눈치 챘을 때, 당신은 당신의 파서가 그 값이 다음과 같은 사전이라는 사전을 제공한다는 것을 알고 있습니다.

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

보너스로 귀하의 문제에 대해 다른 해결책을 제공하고 싶습니다. 특히 내부 키의 존재를 확인해야 할 때 일반적으로 지루한 중첩 사전을 다루는 것 같습니다.

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

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.


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


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 = mydict.values()
>>>mylist[0]
{'American':'16', 'Mexican':10, 'Chinese':5},
>>>mylist[1]
{'Arabian':'25','Indian':'20'}

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

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...


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.

참고URL : https://stackoverflow.com/questions/5404665/accessing-elements-of-python-dictionary-by-index

반응형