假设我有大量不同颜色的水果,例如24个蓝色香蕉,12个青苹果,0个蓝色草莓等.我想用Python中的数据结构组织它们,以便于选择和排序.我的想法是将它们放入一个以元组为键的字典中,例如,
{ ('banana', 'blue' ): 24,
('apple', 'green'): 12,
('strawberry','blue' ): 0,
...
}
Run Code Online (Sandbox Code Playgroud)
甚至是字典,例如,
{ {'fruit': 'banana', 'color': 'blue' }: 24,
{'fruit': 'apple', 'color': 'green'}: 12,
{'fruit': 'strawberry','color': 'blue' }: 0,
...
}
Run Code Online (Sandbox Code Playgroud)
例如,我想检索所有蓝色水果或所有颜色的香蕉的列表,或者通过水果的名称对该字典进行排序.有没有办法以干净的方式做到这一点?
很可能是以元组为键的字典不是处理这种情况的正确方法.
欢迎所有建议!
我是新来的Python,和我熟悉的实现屈德宁在其他 语言.Python是否内置了这样的数据结构,或者在常用的库中可用?
为了说明"multimap"的含义:
a = multidict()
a[1] = 'a'
a[1] = 'b'
a[2] = 'c'
print(a[1]) # prints: ['a', 'b']
print(a[2]) # prints: ['c']
Run Code Online (Sandbox Code Playgroud)