将字典(带有键和值列表)转换为字典列表
To convert a dict (with list of keys and values) into list of dict
我有一个包含键列表的字典,值单独存储在列表列表中:
obj = {
'keys': ['key1', 'key2', 'key3'],
'items': [['value1', 'value2', 'value3'], ['value4', 'value5', 'value6'], ['value7', 'value8', 'value9']]
}
期望的输出是 'merge' 它们变成这样的字典列表:
[
{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'},
{'key1': 'value4', 'key2': 'value5', 'key3': 'value6'},
{'key1': 'value7', 'key2': 'value8', 'key3': 'value9'}
]
我试过这种直接的方法
result = []
for item in obj['items']:
result.append(dict(zip(obj['keys'], item)))
并将其缩短为
[dict(zip(obj['keys'], item)) for item in obj['items']]
是否有其他替代方法来实现所需的输出?
我可以知道这个 'merge' 操纵的名称吗?
您可以使用 pandas
:
import pandas as pd
obj = {
'keys': ['key1', 'key2', 'key3'],
'items': [['value1', 'value2', 'value3'], ['value4', 'value5', 'value6'], ['value7', 'value8', 'value9']]
}
df = pd.DataFrame(obj['items'], columns=obj['keys'])
df.to_dict(orient='records')
结果:
[{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'},
{'key1': 'value4', 'key2': 'value5', 'key3': 'value6'},
{'key1': 'value7', 'key2': 'value8', 'key3': 'value9'}]
[ dict(zip(obj['keys'], item)) for item in obj['items'] ]
您的最后一行包含以下组件:
列表理解,即[ function(x) for x in list_x ]
压缩 2 个列表,即 zip(list1, list2)
也许这些就是您正在寻找的 'merge' 操作的名称?
我有一个包含键列表的字典,值单独存储在列表列表中:
obj = {
'keys': ['key1', 'key2', 'key3'],
'items': [['value1', 'value2', 'value3'], ['value4', 'value5', 'value6'], ['value7', 'value8', 'value9']]
}
期望的输出是 'merge' 它们变成这样的字典列表:
[
{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'},
{'key1': 'value4', 'key2': 'value5', 'key3': 'value6'},
{'key1': 'value7', 'key2': 'value8', 'key3': 'value9'}
]
我试过这种直接的方法
result = []
for item in obj['items']:
result.append(dict(zip(obj['keys'], item)))
并将其缩短为
[dict(zip(obj['keys'], item)) for item in obj['items']]
是否有其他替代方法来实现所需的输出?
我可以知道这个 'merge' 操纵的名称吗?
您可以使用 pandas
:
import pandas as pd
obj = {
'keys': ['key1', 'key2', 'key3'],
'items': [['value1', 'value2', 'value3'], ['value4', 'value5', 'value6'], ['value7', 'value8', 'value9']]
}
df = pd.DataFrame(obj['items'], columns=obj['keys'])
df.to_dict(orient='records')
结果:
[{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'},
{'key1': 'value4', 'key2': 'value5', 'key3': 'value6'},
{'key1': 'value7', 'key2': 'value8', 'key3': 'value9'}]
[ dict(zip(obj['keys'], item)) for item in obj['items'] ]
您的最后一行包含以下组件:
列表理解,即
[ function(x) for x in list_x ]
压缩 2 个列表,即
zip(list1, list2)
也许这些就是您正在寻找的 'merge' 操作的名称?