[英]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.