yourlist = [{'name': 'book', 'number': 5}, {'name': 'pen', 'number': 4}]
dict不是應該都是這樣表示的嗎?
mydict = { "book": 5,
"pen": 4,
"cholk": 3,
"eraser": 2}
當你輸入了 "book",取得yourlist就得一個個來,有100萬個元素,就要跑100萬次(最糟的情況)
want = "book"
result = list(filter(lambda yourlist: yourlist['name'] == want , yourlist))
print(result["name"], str(result["number"]))
用純dict就是
print(want ,mydict[want])
重新排一下
import sys
import os
yourlist = [{'name': 'book', 'number': 5}, {'name': 'pen', 'number': 4}]
mydict = { "book": 5,
"pen": 4,
"cholk": 3,
"eraser": 2}
akey = "book"
result = list(filter(lambda yourlist: yourlist['name'] == akey, yourlist))[-1]
print(result["name"], result["number"])
print(akey ,mydict[akey])
yourlist = [{'name': 'book', 'number': 5}, {'name': 'pen', 'number': 4}]
你把他list裡所有的元素(dict)當物件看,應該就沒這問題了。
有時候web api打進來就是這樣,不會是整個dict。
不過真的用list 跑 lambda ,就真的是list從頭跑到尾,真的要跑大本字典,速度真的會有差,可以試試
def query(name):
mylist = [{'name':'book','number':5},{'name':'pen','number':4}]
target = list(filter(lambda mylist: mylist['name'] == name, mylist))
return 'name: {}, number: {}'.format(target[0]['name'], target[0]['number']) if len(target) else 'No result'
print(query('pen'))
直接 return target 就好了,你這樣只能傳回第一筆。
我會這樣寫。
mylist = [{'name':'book','number':5},{'name':'pen','number':4}]
def query(queryKey, queryValue, queryLST):
target = list(filter(lambda x: x[queryKey] == queryValue, queryLST))
return target if target else 'No result'
print(query('name', 'book', mylist))
我想說他的 name 不會有重複的
所以秀第一筆就好
list = [{'name':'book','number':5},{'name':'pen','number':4}]
def get_dict_number(arg):
for i in list:
if i['name']==arg:
return i['number']
key_name = input("請輸入英文單字(book或pen):")
key_number= get_dict_number(key_name)
if key_number!=None:
print("Name:%s\nNumber:%s"%(key_name,get_dict_number(key_name)))
else:
print("沒有符合的結果.")