Python: Tuples/dictionaries as keys, select, sort

后端 未结 8 1704
独厮守ぢ
独厮守ぢ 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条回答
  •  [愿得一人]
    2020-12-07 08:57

    You could have a dictionary where the entries are a list of other dictionaries:

    fruit_dict = dict()
    fruit_dict['banana'] = [{'yellow': 24}]
    fruit_dict['apple'] = [{'red': 12}, {'green': 14}]
    print fruit_dict
    

    Output:

    {'banana': [{'yellow': 24}], 'apple': [{'red': 12}, {'green': 14}]}

    Edit: As eumiro pointed out, you could use a dictionary of dictionaries:

    fruit_dict = dict()
    fruit_dict['banana'] = {'yellow': 24}
    fruit_dict['apple'] = {'red': 12, 'green': 14}
    print fruit_dict
    

    Output:

    {'banana': {'yellow': 24}, 'apple': {'green': 14, 'red': 12}}

提交回复
热议问题