简体   繁体   English

如何将键和值从字典连接到列表?

[英]How to concat key and value from dictionary to list?

I'm trying to concatenate key and value from a dictionary, and I would like to put them in a sublist according to the key; 我正在尝试将字典中的键和值连接起来,我想根据键将它们放在子列表中; but I do not succeed. 但我没有成功。 So far what I have (working on Python 2.7): 到目前为止,我所拥有的(在Python 2.7上工作):

I managed to concatenate the key and values, but not to split them in different sublists. 我设法将键和值连接起来,但没有将它们拆分到不同的子列表中。

dict = {'v1':[1, 2, 3], 'v2': [1, 2, 3, 4]}

concat = []
for key in dict.keys():
    vals = dict [key]
    for v in vals:
        concat.append(str(key + '_' + str(v)))

I get: 我得到:

 ['v1_1', 'v1_2', 'v1_3', 'v2_1', 'v2_2', 'v2_3', 'v2_4']

but I would like: 但我想:

[['v1_1', 'v1_2', 'v1_3'], ['v2_1', 'v2_2', 'v2_3', 'v2_4']]
dict = {'v1':[1, 2, 3], 'v2': [1, 2, 3, 4]}
res=[]
for key in dict.keys():
    vals = dict [key]
    res.append([ key+'_'+str(v) for v in vals])

You could use this list comprehension. 您可以使用此列表理解。 Python 3.6+. Python 3.6以上版本。

>>> [[ f'{k}_{x}' for x in dict[k] ] for k in dict]
[['v1_1', 'v1_2', 'v1_3'], ['v2_1', 'v2_2', 'v2_3', 'v2_4']]

Or for Python < 3.6. 或对于Python <3.6。

>>> [[ '%s_%d' % (k,x)  for x in d[k] ] for k in d]
[['v1_1', 'v1_2', 'v1_3'], ['v2_1', 'v2_2', 'v2_3', 'v2_4']]

You are appending to the same list on both levels of your for loop. 您将在for循环的两个级别上追加到同一列表。 Change it to 更改为

for key in dict.keys():
    sublist = []
    vals = dict [key]
    for v in vals:
        sublist.append(str(key + '_' + str(v)))
    concat.append(sublist)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从列表中的键获取字典值? - How to get dictionary value from key in a list? 如何在 Python 中的字典列表中使用另一个键列表中的值在字典中创建一个新键? - How to create a new key in dictionary with value from another key list from a list of dictionary in Python? 如何迭代字典中的列表,从键和 append 中获取值以列出? - How to iterate list in dictionary, get value from key and append to list? 如何将列表中的值引用到字典键值? - How can I reference a value from a list to the dictionary key value? 当值是列表时,如何打印字典中的每个键和值? - How to print every key and value from a dictionary when the value is a list? 合并值(清单)来自 <key, value> 在字典中 - Joining value(list) from <key, value> in dictionary 如何从字典键中的一个值获取整个列表? - How to get entire list from just one value in a dictionary key? 如何使用循环列表中的键将值添加到字典中 - How can I add the value into dictionary with the key from looping the list 如何从字典的列表元素中打印出最高值的键? - How to print the key of highest value from the list's element of the dictionary? 如何从python中具有相同键和值的字符串列表创建字典 - How to create a dictionary from a list of strings with same key, value in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM