[英]How to create a dictionary, where the key is the key of a dictionary of lists and the value is the longest list
我有這本字典列表字典:
dict_countries ={'uk': [{'datetime': '1955-10-10 17:00:00', 'city': 'chester'},{'datetime': '1956-09-10 13:00:00', 'city': 'london'}],'us': [{'datetime': '1974-10-10 23:00:00', 'city': 'hudson'}]}
到目前為止,我已經寫了這個 function(我不能使用元組)。 該函數必須返回一個字典,其中 Key 是景點最多的國家的名稱(其列表中的字典),值是景點的數量:
def country_with_most_sights(dict_countries:dict)-> dict:
record_dict = {}
for country in dict_countries
N_sights = len(each_country)
if N_sights > record_dict[past_country]:
past_country = ***country´s name***
record_dict[past_country] = N_sights
return record_dict
期望的結果將是 record_dict 為:
record_dict = {uk:2}
有很多方法可以做到這一點。 這里有一些:
找到每個值的長度,然后使用max
和key
參數找到長度最長的項目。
def country_with_most_sights(dict_countries:dict)-> dict: return dict([max(((k, len(v)) for k, v in dict_countries.items()), key=lambda x: x[1])])
解釋:
items()
的max()
。dict.items()
的每個元素都是一個包含鍵和值的元組。((k, len(v)) for k, v in dict_countries.items())
將其轉換為包含鍵和值長度的元組 僅使用字典的.keys()
並在您的 lambda 中使用此鍵索引到原始字典。
def country_with_most_sights(dict_countries:dict)-> dict: max_key = max(dict_countries.keys(), key=lambda k: len(dict_countries[k])) max_val = len(dict_countries[k]) return {max_key: max_val}
遍歷字典的鍵並跟蹤最長的值。 然后返回該密鑰及其長度:
def country_with_most_sights(dict_countries:dict)-> dict: longest_country = "none" num_sights = 0 for k, v in dict_countries.items(): if len(v) > num_sights: longest_country = k num_sights = len(v) return {longest_country: num_sights}
解釋:
dict.items()
longest_country
和num_sights
變量中。dict_countries = {'uk': [{'datetime': '1955-10-10 17:00:00', 'city': 'chester'},
{'datetime': '1956-09-10 13:00:00', 'city': 'london'}],
'us': [{'datetime': '1974-10-10 23:00:00', 'city': 'hudson'}]}
val = 0
k = ''
for key in dict_countries.keys():
qqq = len(dict_countries[key])
if qqq > val:
val = qqq
k = key
ttt = {k: val}
Output
{'uk': 2}
通過變量“val”更新列表的最大大小。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.