2014-12-11 5 views
0

나는 JSON을 다루고 있고 파이썬에서 파싱하고있다. 나는이 구문을 이해할 수없는 한 부분을 가지고있다. 그래서 내 JSON은 다음과 같습니다.목록의 목록에있는 Dict에 액세스하기

u'line_items':[ 
    { 
     u'product':{ 
      u'weight':0.5, 
      u'regular_price':u'$40.00', 
      u'name_short':u'Name', 
      u'currency':u'USD', 
      }, 
    { 
     u'product':{ 
      u'weight':None, 
      u'regular_price':u'$17.00', 
      u'name_short':u'Map of the World Jumbo Puzzle', 
      u'currency':u'USD', 
    } 
    ] 

때때로 line_items 목록에 두 개 이상의 제품이 있습니다. line_items에서 제품 dicts를 반복하는 구문은 무엇입니까? 나는 노력하고있어

for j in i['line_items'] 
    product = j['product'] 

그러나 첫번째 제품에서만 작동한다. 또한 iline_items을 포함하는 더 큰 dict의 열거 자 역할을합니다. 제품 이상

+1

i [ 'line_items']'는 사전이 아닌 목록입니다. 'd에 대해 i [ 'line_items'] : d [ 'product']에있는 것이 무엇이든 : 가장 안쪽에있는 사전에있는 키를 얻는 것 ('no 's'). – jonrsharpe

+0

잘못된 구문을 입력하셨습니다 (u'line_items ': 저희에게 알려주지 않은 내용입니다). 당신이 우리에게 짧은, 일하는 프로그램을 제공한다면, 우리는 대답 할 수있는 가능성이 더 높습니다. – tdelaney

답변

-1

으로 반복 :

for product in i['line_items']: 
    # prints single products 
    print product 

아니면 (다음 예에 index_in_list에 대한) 제품 인덱스를 필요로하는 경우 :

: 단일 제품의 키를 통해

for index_in_list in range(len(i['line_items'])): 
    # prints single products 
    print i['line_items'][index_in_list] 

으로 반복

for product_key in i['line_items'][index_in_list]: 
    # prints product info 
    print product_key, '-', i['line_items']['product'][product_key] 

또는 쉽게 :

당신이 우리에게 난 단지 추측하고 전체 데이터 구조를 제공하지만하지 않았으므로
for product_key, product in i['line_items'][index_in_list].iteritems(): 
    # still has access to 'product_key' if you want to modify it. 
    print product_key, '-', product 
+1

'i [ 'line_items']'**는리스트 **이므로 이것은 TypeError입니다. – jonrsharpe

+0

@jonrsharpe 감사합니다. –

0

, ... 당신은 단지리스트의 한 단계가 있습니다. 제품 딕트 (dicts)를 얻기 위해 그것을 열거하십시오.

for item in i['line_items']: 
    product = item['product'] 
    weight = product['weight'] 
    # sanity check 
    print("product: %s, weight: %s" % (product['name_short'], weight)) 
+0

이렇게하면 line_items의 첫 번째 제품에만 적용됩니다 (편집 참조). – Kat

+0

@kat - 나는 그것이 모두를 위해 일할 것이라고 생각합니다. 귀하의 예제에서'line_items'는 dicts의 목록입니다. 'for' 루프는 그 dicts리스트를 반복하고, 각각을 위해 body를 실행합니다. – tdelaney

관련 문제