是否有类似字典的数据结构,可以搜索'key'和'value' [英] Is there a dictionary-like datastructure that would allow searches for 'key' and for 'value'
问题描述
我需要一个我的小Python程序的结构来保存最多500个名称的列表,每个名称都有一个数字。这些名字将是独一无二的,但数字将重复(经常)。我首先想到了一个字典,但我也需要能够搜索数字,例如我需要将所有 2
更改为 3
。你会推荐什么
我是Python的新手,所以我相信我忽略了一个简单的解决方案。
code>(Spiderman,1)
(Dr. House,2)
(Jon Skeet,1)
pre>
解决方案您可以使用dict,并按如下所示搜索:
names = {Spiderman:1,Dr. House:2,Jon Skeet:1}
produce_keys = [k for k,v在names.iteritems()如果v == 1]
#返回['蜘蛛侠','Jon Skeet']
然后,您可以执行以下操作:
names.update(dict((k,名称[k] + 1)for k in generated_keys))
现在将更新名称为:
{'Jon Skeet':2,'Dr. House':2,'蜘蛛侠':2}
I need a structure for my little Python program to save a list of max 500 names with one number each. The names would be unique, but the numbers would repeat (often). I first thought of a dictionary, but I also need to be able to search for the numbers, for instance I would need to change all
2
to3
. What would you recommend?I am new to Python, so I am sure I overlooked a simple solution.
("Spiderman",1) ("Dr. House",2) ("Jon Skeet",1)
解决方案You can use a dict, and search by value like so:
names = {"Spiderman":1, "Dr. House":2, "Jon Skeet":1} resulting_keys = [k for k, v in names.iteritems() if v == 1] # returns ['Spiderman', 'Jon Skeet']
Then you can do something like:
names.update(dict((k,names[k] + 1) for k in resulting_keys))
Which will now update names to:
{'Jon Skeet': 2, 'Dr. House': 2, 'Spiderman': 2}
这篇关于是否有类似字典的数据结构,可以搜索'key'和'value'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!