Python: Tuples/dictionaries as keys, select, sort

后端 未结 8 1731
独厮守ぢ
独厮守ぢ 2020-12-07 07:53

Suppose I have quantities of fruits of different colors, e.g., 24 blue bananas, 12 green apples, 0 blue strawberries and so on. I\'d like to organize them in a data structur

8条回答
  •  猫巷女王i
    2020-12-07 08:38

    You want to use two keys independently, so you have two choices:

    1. Store the data redundantly with two dicts as {'banana' : {'blue' : 4, ...}, .... } and {'blue': {'banana':4, ...} ...}. Then, searching and sorting is easy but you have to make sure you modify the dicts together.

    2. Store it just one dict, and then write functions that iterate over them eg.:

      d = {'banana' : {'blue' : 4, 'yellow':6}, 'apple':{'red':1} }
      
      blueFruit = [(fruit,d[fruit]['blue']) if d[fruit].has_key('blue') for fruit in d.keys()]
      

提交回复
热议问题