努力设计一本基于上一本书的词典

2024-07-04 16:48:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下dicti_1

{'2017-09-01': ['PRUEBAPRUEBA', 'PRUEBA123123'], 
 '2017-10-03': ['PRUEBAPRUEBA', 'PRUEBA123123'], 
 '2017-11-08': ['PRUEBAPRUEBA', 'PRUEBA123123'], 
 '2017-12-03': ['PRUEBA123123']}

我期待检查最新键中出现的值(因为是日期):

为了检查与最新键对应的最新值,我所做的是:

编辑:从@COLDSPEED输入我整理字典,我使用@Devin Jeanpierre 的答案,以便使用运算符模块对字典进行排序:How do I sort a dictionary by value?

sorted_dict = sorted(dicti_1.items(), key=operator.itemgetter(0))

latest_key=list(sorted_dict.keys())[-1]

return sorted_dict[latest_key]

在此之后,我期待着创建一个字典,其中包含最新日期的键和出现的值:

return {latest_key:sorted_dict[latest_key]}

输出:

{'2017-12-03': ['PRUEBA123123']}

但是在我的特殊情况下,有一个最新值2017-12-03,它对应于PRUEBA123123,还有一个不同的值PRUEBAPRUEBA,它的最新日期是2017-11-08。 因此,我期望的输出是这样的:

new_dicti=

{'2017-12-03': ['PRUEBA123123'], '2017-11-08': ['PRUEBAPRUEBA']}

我面临的问题是如何为每一个不同的值设计最新日期的新目录

非常感谢你的帮助。你知道吗


Tags: key答案编辑return字典latest整理dict
2条回答

请检查这是否有效-

import collections
dicti_1 = {'2017-09-01': ['PRUEBAPRUEBA', 'PRUEBA123123'],  
 '2017-11-08': ['PRUEBAPRUEBA', 'PRUEBA123123'], 
 '2017-10-03': ['PRUEBAPRUEBA', 'PRUEBA123123'],
 '2017-12-03': ['PRUEBA123123']}

dicti_2 = collections.OrderedDict(sorted(dicti_1.items()))
print(dicti_2)
my_dict2 = { z:x for x,y in dicti_2.items() for z in y }

print(my_dict2)
output = {}
for key, value in my_dict2.items():
    if value in output:
        output[value].append(key)
    else:
        output[value] = [key]
print(output)

我的方法是首先根据关键字对dict进行排序,然后将dict值中的唯一项存储到一个全新的字典中。你知道吗

for date in sorted(d.keys(), reverse=True):
    for l in d[date]:
        if l not in new_dict:
            new_dict[l] = date

它将产生如下输出

{'PRUEBA123123': '2017-12-03', 'PRUEBAPRUEBA': '2017-11-08'}

相关问题 更多 >

    热门问题