簡體   English   中英

如何創建字典,其中鍵是列表字典的鍵,值是最長列表

[英]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}

有很多方法可以做到這一點。 這里有一些:

  1. 找到每個值的長度,然后使用maxkey參數找到長度最長的項目。

     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())將其轉換為包含鍵和值長度的元組
    • 通過指定 lambda function,我們使用此元組的第二個元素(即值的長度)作為找到最大值的標准。
  2. 僅使用字典的.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}
  3. 遍歷字典的鍵並跟蹤最長的值。 然后返回該密鑰及其長度:

     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_countrynum_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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM