我做了一个函数,可以在 "字典 "中查找年龄并显示匹配的名字。
dictionary = {'george' : 16, 'amber' : 19}
search_age = raw_input("Provide age")
for age in dictionary.values():
if age == search_age:
name = dictionary[age]
print name
我知道如何比较并找到年龄,只是不知道如何显示人名。此外,由于第5行,我得到了一个`KeyError'。我知道这是不正确的,但我不知道如何让它向后搜索。
mydict = {'george':16,'amber':19}
print mydict.keys()[mydict.values().index(16)] # Prints george
或者在Python 3.x中。
mydict = {'george':16,'amber':19}
print(list(mydict.keys())[list(mydict.values()).index(16)]) # Prints george
基本上,它把字典中的值分成一个列表,找到你所拥有的值的位置,并在这个位置上得到键。
更多关于Python 3中的keys()
和.values()
。
https://stackoverflow.com/questions/16228248/python-simplest-way-to-get-list-of-values-from-dict
没有。`dict'不打算以这种方式使用。
for name, age in dictionary.items(): # for name, age in dictionary.iteritems(): (for Python 2.x)
if age == search_age:
print(name)
如果你想同时得到名字和年龄,你应该使用.items()
,它给你钥匙(key, value)
图示。
for name, age in mydict.items():
if age == search_age:
print name
你可以在for
循环中把元组解包成两个独立的变量,然后匹配年龄。
如果你一般要按年龄查询,而且没有两个人有相同的年龄,你也应该考虑把字典反过来。
{16: 'george', 19: 'amber'}
所以你可以通过做以下工作来查询一个年龄段的名字
mydict[search_age]
我一直称它为 "mydict",而不是 "list",因为 "list "是一个内置类型的名称,你不应该把这个名称用于其他东西。
你甚至可以在一行中获得所有具有指定年龄的人的列表。
[name for name, age in mydict.items() if age == search_age]
或者如果每个年龄段只有一个人。
next((name for name, age in mydict.items() if age == search_age), None)
如果没有该年龄段的人,则只给你 "无"。
最后,如果dict'很长,而且你在Python 2上,你应该考虑使用
.iteritems()而不是
.items()`,就像Cat Plus Plus在他的答案中做的那样,因为它不需要对列表进行复制。
<!--语言。 python --> 我想指出哪种方法是最快的,以及在什么情况下是有趣的。
下面是我进行的一些测试(在2012年的MacBook Pro上)。
>>> def method1(list,search_age):
... for name,age in list.iteritems():
... if age == search_age:
... return name
...
>>> def method2(list,search_age):
... return [name for name,age in list.iteritems() if age == search_age]
...
>>> def method3(list,search_age):
... return list.keys()[list.values().index(search_age)]
profile.run()
在每个方法上100000次的结果。
方法1:
>>> profile.run("for i in range(0,100000): method1(list,16)")
200004 function calls in 1.173 seconds
方法2:
>>> profile.run("for i in range(0,100000): method2(list,16)")
200004 function calls in 1.222 seconds
方法三:{{10688135}}。
>>> profile.run("for i in range(0,100000): method3(list,16)")
400004 function calls in 2.125 seconds
因此,这表明对于一个小的 dict,方法 1 是最快的。 这很可能是因为它返回的是第一个匹配项,而不是像方法2那样返回所有的匹配项(见下面的注释)。
有趣的是,在我的一个有2700个条目的dict上执行同样的测试,我得到了完全不同的结果(这次运行10000次)。
方法一:
>>> profile.run("for i in range(0,10000): method1(UIC_CRS,'7088380')")
20004 function calls in 2.928 seconds
方法2:
>>> profile.run("for i in range(0,10000): method2(UIC_CRS,'7088380')")
20004 function calls in 3.872 seconds
方法3:
>>> profile.run("for i in range(0,10000): method3(UIC_CRS,'7088380')")
40004 function calls in 1.176 seconds
所以在这里,方法3是*快的。 只是说明你的dict的大小会影响你选择哪种方法。
注释。 方法2会返回一个所有*名字的列表 而方法1和方法3只会返回第一个匹配的名字。 我还没有考虑内存的使用。 我不确定方法3是否会创建2个额外的列表(keys()和values())并将它们存储在内存中。
您可以通过dict.keys()
、dict.values()
和list.index()
等方法来获取key,请看下面的代码示例。
names_dict = {'george':16,'amber':19}
search_age = int(raw_input("Provide age"))
key = names_dict.keys()[names_dict.values().index(search_age)]
我觉得这个[答案][1]很有效,但对我来说不是很容易读懂。
为了更清楚,你可以把字典的键和值反过来。 这就是让键值和值键,如[这里][2]所示。
mydict = {'george':16,'amber':19}
res = dict((v,k) for k,v in mydict.iteritems())
print(res[16]) # Prints george
或
mydict = {'george':16,'amber':19}
dict((v,k) for k,v in mydict.iteritems())[16]
这与另一个[答案][3]基本相同。
[1]: https://stackoverflow.com/a/13149770/7127519 [2]: https://stackoverflow.com/a/1031878/7127519 [3]: https://stackoverflow.com/a/24012167/7127519
这是我对这个问题的看法。 :) 我刚开始学习Python,所以我称之为。
quot;初学者的可理解性
quot;
解决方案。
#Code without comments.
list1 = {'george':16,'amber':19, 'Garry':19}
search_age = raw_input("Provide age: ")
print
search_age = int(search_age)
listByAge = {}
for name, age in list1.items():
if age == search_age:
age = str(age)
results = name + " " +age
print results
age2 = int(age)
listByAge[name] = listByAge.get(name,0)+age2
print
print listByAge
.
#Code with comments.
#I've added another name with the same age to the list.
list1 = {'george':16,'amber':19, 'Garry':19}
#Original code.
search_age = raw_input("Provide age: ")
print
#Because raw_input gives a string, we need to convert it to int,
#so we can search the dictionary list with it.
search_age = int(search_age)
#Here we define another empty dictionary, to store the results in a more
#permanent way.
listByAge = {}
#We use double variable iteration, so we get both the name and age
#on each run of the loop.
for name, age in list1.items():
#Here we check if the User Defined age = the age parameter
#for this run of the loop.
if age == search_age:
#Here we convert Age back to string, because we will concatenate it
#with the person's name.
age = str(age)
#Here we concatenate.
results = name + " " +age
#If you want just the names and ages displayed you can delete
#the code after "print results". If you want them stored, don't...
print results
#Here we create a second variable that uses the value of
#the age for the current person in the list.
#For example if "Anna" is "10", age2 = 10,
#integer value which we can use in addition.
age2 = int(age)
#Here we use the method that checks or creates values in dictionaries.
#We create a new entry for each name that matches the User Defined Age
#with default value of 0, and then we add the value from age2.
listByAge[name] = listByAge.get(name,0)+age2
#Here we print the new dictionary with the users with User Defined Age.
print
print listByAge
.
#Results
Running: *\test.py (Thu Jun 06 05:10:02 2013)
Provide age: 19
amber 19
Garry 19
{'amber': 19, 'Garry': 19}
Execution Successful!
考虑使用Pandas。 正如William McKinney'的"Python for Data Analysis'。
另一种思考Series的方式是作为一个固定长度、有序的 >.dict,因为它是索引值到数据值的映射。 dict,因为它是索引值到数据值的映射。 它可以是
在很多情况下都会用到dict。
import pandas as pd
list = {'george':16,'amber':19}
lookup_list = pd.Series(list)
要查询您的系列,请执行以下操作。
lookup_list[lookup_list.values == 19]
这就产生了。
Out[1]:
amber 19
dtype: int64
如果你需要对输出做任何其他的事情,将其转换为 将答案列成清单也许会有用。
answer = lookup_list[lookup_list.values == 19].index
answer = pd.Index.tolist(answer)
在这里,recover_key需要在字典中找到dictionary和value,然后我们在dictionary中循环,并与value进行比较,然后返回那个特定的key。 然后,我们在 dictionary 中循环,并与 value 中的键进行比较,然后返回那个特定的键。
def recover_key(dicty,value):
for a_key in dicty.keys():
if (dicty[a_key] == value):
return a_key
这是我对它的看法。 这样有利于显示多个结果,以备不时之需。 所以我把列表也加了进去
myList = {'george':16,'amber':19, 'rachel':19,
'david':15 } #Setting the dictionary
result=[] #Making ready of the result list
search_age = int(input('Enter age '))
for keywords in myList.keys():
if myList[keywords] ==search_age:
result.append(keywords) #This part, we are making list of results
for res in result: #We are now printing the results
print(res)
就是这样... ...