python 如何将元组列表转换为固定键目录格式

How to convert list of tuple to fixed key directory format in python

我尝试将元组转换为以下格式

    [(1597209852, 'p'), ('o',1597209851)]

进入这个:

    [  {"key":"p" ,"value": 1597209852  },{"key":"o" ,"value": 1597209851  }

这是我的代码,但不起作用:

    po=[(1597209852, 'p'), (1597209851, 'o')]
    convertedlist = [dict(one=dd[0], two=dd[1])] for dd in po]

我的问题顺序不同。

从你对输入输出的描述来看,你似乎只需要:

def func(arr):
    return [{"key": item[1], "value": item[0]} for item in arr]

这是您要找的吗?

po = [(1597209852, 'p'), (1597209851, 'o')]
newdict = {y:x for x, y in po}

输出:

{'p': 1597209852, 'o': 1597209851}