如何处理该词典中的每个日期键/值对?

时间:2018-08-10 07:51:49

标签: python-3.x dictionary

我在python中有这个字典数组。

array_dict  = [
                    {'Name': 'John', 'Date': '2/18/1998', 'Pay': 21.63},
                    {'Name': 'John', 'Date': '7/7/1999', 'Pay': 15.87}
              ]

我想将字典中的每个日期键对都转换成这样;

out_dict = [
                {'Name': 'John', 'Date': '18-02-1998', 'Pay': 21.63},
                {'Name': 'John', 'Date': '07-07-1999', 'Pay': 15.87}
           ]

我知道如何进行日期转换。进行转换的代码是这样的;

datetime.strptime(date_str, "%m/%d/%Y").strftime("%d-%m-%Y") 

其中date_str包含日期字符串,例如'2/18/1998'

如何在字典中的所有对上应用此转换代码?

2 个答案:

答案 0 :(得分:1)

如果实际上只有这三个键,则可以使用列表理解:

out_dict = [
    {
        'Name': d['Name'],
        'Pay': d['Pay'],
        'Date': datetime.strptime(d['Date'], "%m/%d/%Y").strftime("%d-%m-%Y"),
    } for d in array_dict
]

否则,我将其复制并循环修改:

out_dict = []
for d in array_dict:
    out_dict.append(dict(d))  # make a copy
    out_dict[-1]['Date'] = datetime.strptime(d['Date'], "%m/%d/%Y").strftime("%d-%m-%Y")

答案 1 :(得分:1)

使用dict.update

例如:

import pprint
from datetime import datetime
array_dict  = [
                    {'Name': 'John', 'Date': '2/18/1998', 'Pay': 21.63},
                    {'Name': 'John', 'Date': '7/7/1999', 'Pay': 15.87}
              ]

for i in array_dict:
    i.update({"Date": datetime.strptime(i["Date"], "%m/%d/%Y").strftime("%d-%m-%Y") })
pprint.pprint(array_dict)

输出:

[{'Date': '18-02-1998', 'Name': 'John', 'Pay': 21.63},
 {'Date': '07-07-1999', 'Name': 'John', 'Pay': 15.87}]