Python如何将这种类型的列表转换为字典

时间:2019-03-21 11:11:43

标签: python

[["4040", ["4040", "1.04862754", 4]], ["4040.1", ["4040.1", "0.25906621", 1]], ["4040.2", ["4040.2", "0.954", 1]]]

我想要的是

{"4040": ["4040", "1.04862754", 4]}, {"4040.1": ["4040.1", "0.25906621", 1]}, {"4040.2": ["4040.2", "0.954", 1]}

我想将此数据以json格式发送到redis,但转换时遇到困难。实际上,我已经在字典中写入了此数据,但是在发送给Redis之前,我需要对键进行排序,以便python将其转换为列表。

4 个答案:

答案 0 :(得分:3)

使用切片:

print({x[0]: x[1:] for x in lst})

输出

{'4040': [['4040', '1.04862754', 4]], '4040.1': [['4040.1', '0.25906621', 1]], '4040.2': [['4040.2', '0.954', 1]]}

OR

print(dict(lst))

输出

{'4040': ['4040', '1.04862754', 4], '4040.1': ['4040.1', '0.25906621', 1], '4040.2': ['4040.2', '0.954', 1]}

OR

如果要分隔字典列表:

print([{x[0]: x[1]} for x in lst]) 

输出

[
   {'4040': ['4040', '1.04862754', 4]}, {'4040.1': ['4040.1', '0.25906621', 1]}, {'4040.2': ['4040.2', '0.954', 1]}
]

OR

(通常情况很简单,但我们自己会使它们复杂化)

print([{k:v} for k, v in lst])

输出

[
  {'4040': ['4040', '1.04862754', 4]}, {'4040.1': ['4040.1', '0.25906621', 1]}, {'4040.2': ['4040.2', '0.954', 1]}
]

答案 1 :(得分:2)

编辑:刚看到您想要三个字典,相应地更改了代码。

my_list = [["4040", ["4040", "1.04862754", 4]], ["4040.1", ["4040.1", "0.25906621", 1]], ["4040.2", ["4040.2", "0.954", 1]]]

result = []

for elem in my_list:
    my_dict = {elem[0]: elem[1]}
    result.append(my_dict)

print(result)

输出:

[
  {'4040': ['4040', '1.04862754', 4]},
  {'4040.1': ['4040.1', '0.25906621', 1]},
  {'4040.2': ['4040.2', '0.954', 1]}
]

或者,如注释中所指出的,使用list comprehension并为自己节省大量的行:

result = [{k:v} for k, v in my_list]

这应该做您想要的。

答案 2 :(得分:2)

如果要将列表转换为词典列表,则列表理解就足够了:

>>> list_of_kv = [["4040", ["a", "b", 4]], ["4040.1", ["d", "e", 1]]]

>>> [{k: v} for k, v in list_of_kv]
[{'4040': ['a', 'b', 4]}, {'4040.1': ['d', 'e', 1]}]

如果您只想要一个字典,则内置dict类可以处理它:

>>> dict(list_of_kv)
{'4040': ['a', 'b', 4], '4040.1': ['d', 'e', 1]}

答案 3 :(得分:0)

尝试:

>>> L = [["4040", ["4040", "1.04862754", 4]], ["4040.1", ["4040.1", "0.25906621", 1]], ["4040.2", ["4040.2", "0.954", 1]]]
>>> dict(map(tuple, L))
{'4040': ['4040', '1.04862754', 4], '4040.1': ['4040.1', '0.25906621', 1], '4040.2': ['4040.2', '0.954', 1]}

map(tuple, L)L[0]L[1],...转换为元组。 dictk, v元组转换为字典条目。