在Python 3.6中,我有一個像下面這樣的列表,並且無法弄清楚如何正確搜索這些值。所以,如果我給了下面的搜索字符串,我需要搜索標題和標籤的值以及哪個匹配最多的值,我會返回id,如果有相同數量的許多不同圖像(id)的比賽,那麼標題首先按字母順序排列的人將被退回。另外,它應該不是區分大小寫的。所以在代碼中,我有搜索作爲我的術語來搜索,它應該返回第一個id值,而是返回不同的值。如何用Python中的字典搜索嵌套列表?
image_info = [
{
"id" : "34694102243_3370955cf9_z",
"title" : "Eastern",
"flickr_user" : "Sean Davis",
"tags" : ["Los Angeles", "California", "building"]
},
{
"id" : "37198655640_b64940bd52_z",
"title" : "Spreetunnel",
"flickr_user" : "Jens-Olaf Walter",
"tags" : ["Berlin", "Germany", "tunnel", "ceiling"]
},
{
"id" : "34944112220_de5c2684e7_z",
"title" : "View from our rental",
"flickr_user" : "Doug Finney",
"tags" : ["Mexico", "ocean", "beach", "palm"]
},
{
"id" : "36140096743_df8ef41874_z",
"title" : "Someday",
"flickr_user" : "Thomas Hawk",
"tags" : ["Los Angeles", "Hollywood", "California", "Volkswagen", "Beatle", "car"]
}
]
my_counter = 0
search = "CAT IN BUILding"
search = search.lower().split()
matches = {}
for image in image_info:
for word in search:
word = word.lower()
if word in image["title"].lower().split(" "):
my_counter += 1
print(my_counter)
if word in image["tags"]:
my_counter +=1
print(my_counter)
if my_counter > 0:
matches[image["id"]] = my_counter
my_counter = 0
什麼,當你說「返回」你的意思是?你沒有返回任何東西?你的預期產出是什麼,它與你擁有的產品有什麼不同?你能更明確嗎? –
我運行了你的代碼,它給了我匹配詞典中的第一個ID。但是,標籤存在一個錯誤。您將搜索字符串中的單詞縮寫爲小寫,而不是標記中的單詞,但標記包含一些大寫的單詞。例如,你將無法匹配洛杉磯。 – bouma
@ juanpa.arrivillaga因此,我使用搜索項「CAT IN BUILTING」來搜索列表/字典中的標題和標記的值,並且我希望函數返回找到的匹配項。因此,對於「CAT IN BUILTING」,它應該返回1,並在34694102243_3370955cf9_z找到匹配的ID。如果搜索詞是「在墨西哥海灘建造」,那麼它應該返回34944112220_de5c2684e7_z,因爲它在標籤中有2個匹配項。 – Gray