2013-04-17 3 views
1

나는 최근에 만난 특정 문제에 대해 질문하고 싶습니다.파이썬 사전 배열

예 :

list1 = ['library','book','room','author','description','genre','publish_date','price','title'] 

및 키와 값을 포함하는 사전 키는 list1의 항목이고 값은 그 하위 항목입니다 (예 :

dictionary1 = {'room': ['book'], 'title': [], 'price': [], 'author': [], 'library': [ 'room', 'book'], 'book': ['author', 'title', 'genre', 'price', 'publish_date', 'description'], 'publish_date': [], 'genre': [], 'description': []} 

기본적으로 내가하고 싶은 dictionary1의 항목을 통해 이동하여 특정 키 값도 값 키의 경우, 내가 키 값의 값을 추가 할 수 있습니다.

예를 들어

:

'library': ['room','book'] 

책은 저자, 제목, 장르, 가격, publishdate, 설명이 포함되어 있습니다.

은 내가 라이브러리 키에 모든 항목을 추가하려면, 그래서 보일 것 같은 :

'library': ['room','book','author', 'title', 'genre', 'price', 'publish_date', 'description'], 'publish_date': [], 'genre': [], 'description': []] 
+8

당신은 아무것도 시도? – Maroun

+2

당신의'dictionary1' 예제는 유효하지 않습니다; * 책 키가 두 개 있습니다. –

+0

그것은 볼 수있는 한 두 권의 책 키가 없습니다. 항목을 병합하는 트릭을하는 3 개의 중첩 된 FOR를 시도했지만 전체 사전 전체를 반복하는 방법을 찾지 못했습니다. –

답변

0

큰 문제는 다음과 같습니다. 데이터를 복제하고 싶지 않습니다. 반복 할 때 데이터를 먹지 않으려합니다.

import pprint 

    def main(): 
     inlist = ['library','book','room','author','description','genre','publish_date','price','title'] 
     mydict = {'room': ['book'], 'title': [], 'price': [], 'author': [], 'library': [ 'room', 'book'], 'book': ['author', 'title', 'genre', 'price', 'publish_date', 'description'], 'publish_date': [], 'genre': [], 'description': []} 

     for item in inlist: 
      values = set(mydict.get(item, [])) 
      workingset = values.copy() # preserve the original set of items so iterating doesn't go nuts 
      for potential_key in values: 
       # we're going to cast into sets to add them, then recast into lists 
       workingset.update(set(mydict.get(potential_key, []))) 

      if values: 
       mydict[item] = list(workingset) 

     pprint.pprint(mydict) 
    if __name__ == '__main__': 
     main() 
+0

코드가 거의 제대로 작동하는 것처럼 보입니다 만, 코드 (동일한 목록과 딕트)를 사용할 때 한 가지 더 묻고 싶습니다. 'room' : [ '책', '게시 _', '설명', '제목', '장르', '가격', '저자', 와 '라이브러리': [ '책', '방 '], 도서관에서 방에있는 항목을 갖고 싶습니다. 도서관이 방을 가리키고 방이 책을 가리키고 책을 .... 있기 때문에 어떤 방법이 있습니까? 많이 thx :] –

+0

루프, THX 많은 남자 동안 추가 된 문제를 해결! :) –

1

의사 코드 : 우리는 파이썬을 이야기로

dictionary = ...//your input 
dictionaryOut={} 

list=[] 

for key, value in dictionary 
    dictionaryOut[key] = copy(value) 

    if length(value[0]): 
     list=[value[0]] 

    while not empty(list): 
     list.append(dictionary(list[0])) 
     dictionaryOut[key].append(dictionary(list.pop(0)) 

이만큼 그것을해야하고 값에 추가하면 실제로 사전에있는 목록이 업데이트됩니다.

+0

당신의 아이디어를 가져 주셔서 감사합니다 :] –

0

사전 이해가 :

{key: set(values + sum([dictionary1[value] for value in values], [])) 
     for key, values in dictionary1.iteritems()} 
+0

아이디어 감사합니다 :] –