在dict中搜索一个键,并将该键的值赋给一个变量Python

2024-10-04 03:26:19 发布

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

我有这样一句话:

dict_meses = {1: 'Enero', 2: 'Febrero', 3: 'Marzo', 4: 'Abril', 5: 'Mayo', 6: 'Junio', 7: 'Julio', 8: 'Agosto',
              9: 'Setiembre', 10: 'Octubre', 11: 'Noviembre', 12: 'Diciembre'}

我需要将dict中对应月份的字符串改为'14/1/2015'。例如,如果a有'14/1/2015',我需要将其改为'1/Enero/2015'

我试着这样做:

def xxx(days):   -----> days is a list of tuples like this [('14/1/2015', 500), ...]

    dict_months = {1: 'Enero', 2: 'Febrero', 3: 'Marzo', 4: 'Abril', 5: 'Mayo', 6: 'Junio', 7: 'Julio', 8: 'Agosto',
              9: 'Setiembre', 10: 'Octubre', 11: 'Noviembre', 12: 'Diciembre'}
    days_list = []
    for i in days:
        lista = list(i)
        fecha_entera = lista[0].split('/') ---> ['14','1','2015']
        dia = fecha_entera[1] ----------------> '1'
        if int(dia) in dict_meses.keys():
            fecha_entera[1] = ????------------> want to change '1' to 'Enero'
            dias_lista.append(fecha_entera)
    return dias_lista

问题:如何获取与日期所代表的键对应的值

如果我没有解释清楚,就让我知道,我会更加努力

提前感谢您的帮助


Tags: daysdictlistmayolistaagostofechameses
2条回答

对于字符串解决方案,请使用“/1/”上的字符串“replace”函数

lista.replace("/" + dia + "/", "/" + dict_months[int(dia)] + "/")

您可以使用datetime来解析日期,使用%B和srftime来获得所需的输出:

from datetime import datetime
dte = '14/1/2015'
print(datetime.strptime(dte,"%d/%m/%Y").strftime("%d/%B/%Y"))

%B将为您提供区域设置的完整月份名称

In [1]: from datetime import datetime   
In [2]: dte = '14/1/2015'    
In [3]: import locale    
In [4]: locale.setlocale(locale.LC_ALL,"es_SV.utf_8")
Out[4]: 'es_SV.utf_8'    
In [5]: print(datetime.strptime(dte,"%d/%m/%Y").strftime("%d/%B/%Y"))
14/enero/2015

如果每个第一个元素都是日期字符串:

def xxx(days):
    return [datetime.strptime(dte, "%d/%m/%Y").strftime("%d/%B/%Y")
            for dte, _ in days]

如果你想用你的口述:

def xxx(days):
    dict_months = {"1": 'Enero', "2": 'Febrero', "3": 'Marzo', "4": 'Abril', "5": 'Mayo', "6": 'Junio', "7": 'Julio',
                   "8": 'Agosto',
                   "9": 'Setiembre', "10": 'Octubre', "11": 'Noviembre', "12": 'Diciembre'}
    days_list = []
    for sub in map(list, days):
        dy, mn, year = sub[0].split()
        days_list.append("{}/{}/{}".format(dy, dict_months[mn], year))
    return days_list

您应该将键用作字符串,必须转换为int进行比较是没有意义的

相关问题 更多 >