所以,我在python中有一個dict的串列,看起來像這樣:
我有一個dict的串列。
lis =
[
{'action': 'notify', 'type': 'Something', 'Genre': 10, 'date': '2021-05-07 01:59:37'}。
{'action': 'notify', 'type': 'Something Else', 'Genre': 20, 'date': '2021-05-07 01:59:37'}。
...
]
現在我想讓lis以一種方式,使每個單獨的dict使用我將提供的鍵的映射來排序。例如,如果
mapping = {1:'date'/span>, 2: 'Genre', 3:'action', 4:'type'}。
然后,我想讓我的原始字典串列看起來像這樣:
lis =
[
{'date': '2021-05-07 01:59:37', 'genre': 10, 'action': 'notify', 'type': '東西'}。
{'date': '2021-05-07 01:59:37', 'genre': 20, 'action': 'notify', 'type': 'Something Else'}.
...
]
我如何實作這一點?
uj5u.com熱心網友回復:
你可以利用collections.OrderedDict來完成這項任務,如下所示
import collections
order = ['date'/span>, 'Genre'/span>, 'action'/span>, 'type'/span>]
dct1 = {'action': 'notify', 'type': 'Something', 'Genre': 10, 'date': '2021-05-07 01:59:37'}。
dct2 = {'action': 'notify', 'type': 'Something Else', 'Genre': 20, 'date': '2021-05-07 01:59:37'}。
odct1 = collections.OrderedDict.fromkeys(order)
odct1.update(dct1)
odct2 = collections.OrderedDict.fromkeys(order)
odct2.update(dct2)
print(odct1)
print(odct2)
輸出:
OrderedDict([('date', '2021-05-07 01:59: 37'), ('Genre', 10), ('action', 'Notify'), ('type', 'Something')] )
OrderedDict([('date', '2021-05-07 01:59: 37'), ('Genre', 20), ('action', 'notify'), ('type', 'Something Else')])
免責宣告:這假設你要處理的每個dict都有來自order的所有鍵。這個解決方案適用于任何有collections.OrderedDict的python版本,如果你只使用python3.7或更新的版本,你可以使用普通的dict如下
order = ['date', 'Genre', 'action', 'type']
dct1 = dict.fromkeys(order)
dct1.update({'action': 'notify', 'type': 'Something', 'Genre': 10, 'date': '2021-05-07 01:59:37'})
print(dct1)
輸出
{'date': '2021-05-07 01:59:37', 'genre': 10, 'action': 'notify', 'type': '東西'}。
免責宣告仍然成立
uj5u.com熱心網友回復:用一個串列理解:
lis = [
{'action': 'notify', 'type': 'Something', 'Genre': 10, 'date': '2021-05-07 01:59:37'}。
{'action': 'notify', 'type': 'Something Else', 'Genre': 20, 'date': '2021-05-07 01:59:37'}。
]
mapping = {1: 'date', 2: 'Genre', 3:'action', 4:'type'}。
sorted_lis = [
{field: record[field] for field in mapping.values()}。
for record in lis
]
print(sorted_lis)
uj5u.com熱心網友回復:
試一下:
def sort_dct(li, mapping):
return {v: li[v] for k,v in mapping.items()}。
out = []
mapping = {1:date', 2: '流派', 3:'行動', 4:'型別'}。
for li in lis:
out.append(sort_dct(li,mapping))
print(out)
輸出:
[{'date': '2021-05-07 01:59:37',
'Genre': 10,
'action': 'notify',
'type': '東西'}。
{'date': '2021-05-07 01:59:37',
'Genre': 20,
'action': 'notify',
'type': 'Something Else'}] 。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/332770.html
標籤:
