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': []}

基本的に私がやりたいことは、ディクショナリ1の項目を調べて、特定のキーの値が値を持つキーでもある場合、値の値をキーに追加したいです。

例えば:

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

book には、著者、タイトル、ジャンル、価格、発行日、説明が含まれます。

そして、これらすべてのアイテムをライブラリ キーに追加したいので、次のようになります。

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

3 に答える 3

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

これは、Python について話している限り、それを行う必要があり、値に追加すると実際に辞書のリストが更新されます。

于 2013-04-17T14:29:45.930 に答える
0

辞書理解:

{key: set(values + sum([dictionary1[value] for value in values], []))
       for key, values in dictionary1.iteritems()}
于 2013-04-17T15:10:04.377 に答える
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()
于 2013-04-17T14:59:03.033 に答える