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
With keys as tuples, you just filter the keys with given second component and sort it:
blue_fruit = sorted([k for k in data.keys() if k[1] == 'blue'])
for k in blue_fruit:
print k[0], data[k] # prints 'banana 24', etc
Sorting works because tuples have natural ordering if their components have natural ordering.
With keys as rather full-fledged objects, you just filter by k.color == 'blue'
.
You can't really use dicts as keys, but you can create a simplest class like class Foo(object): pass
and add any attributes to it on the fly:
k = Foo()
k.color = 'blue'
These instances can serve as dict keys, but beware their mutability!
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}}