简体   繁体   English

将字典键和值插入python列表

[英]Insert dictionary key and values to a python list

I was trying to insert key and value of my dictionary to a python list.I cant seem to figure it out how to do this. 我试图将字典的键和值插入到python列表中。我似乎无法弄清楚如何做到这一点。

my_dict={test1:[1,2,3,4],test2:[2,3,4,5]}

what I want is 我想要的是

my_list = [['test1', 1,2,3,4], ['test2', 2,3,4,5]]

I am new to python so any help would be appreciated. 我是python的新手,所以将不胜感激。

This should do it 这应该做
We need to iterate over the dictionary, and make a list with the key and values, note that we need to unroll the value array *value in order to append to the list 我们需要遍历字典,并创建一个包含键和值的列表,请注意,我们需要展开值数组*value才能追加到列表中

my_dict={'test1':[1,2,3,4],'test2':[2,3,4,5]}

#Iterate over key and value, and make a list from them, unrolling the value since it is a list
my_list = [[key, *value] for key, value in my_dict.items()]
print(my_list)
#[['test1', 1, 2, 3, 4], ['test2', 2, 3, 4, 5]]

Using a list comprehension 使用列表理解

Ex: 例如:

my_dict={"test1":[1,2,3,4],"test2":[2,3,4,5]}

my_list = [[k] +v for k, v in my_dict.items()]
print(my_list)

Output: 输出:

[['test1', 1, 2, 3, 4], ['test2', 2, 3, 4, 5]]

The other solutions use list comprehensions which may be too complicated for someone who is new to python, so this is a solution without list comprehension. 其他解决方案使用列表推导,这对于python新手来说可能太复杂了,因此这是一个没有列表推导的解决方案。

my_dict={"test1":[1,2,3,4],"test2":[2,3,4,5]}

new_list = []
for key, value in my_dict.items():
    print(key, value)

    temp = []
    temp.append(str(key))
    for a in value:
        temp.append(a)
    new_list.append(temp)

print(new_list) 
# [['test1', 1, 2, 3, 4], ['test2', 2, 3, 4, 5]]

Here's a version without the list comprehension, I remember it took me a couple months to understand the syntax when I was new to python. 这是一个没有列表理解的版本,我记得我刚接触python时花了几个月的时间来理解语法。

my_dict={'test1':[1,2,3,4],'test2':[2,3,4,5]}

my_list = []

for key, value in my_dict.items():
    my_list.append([key, *value]) # the '*value' bit means all elements of the 'value' variable

print(my_list)

FOMO: FOMO:

my_dict={'test1':[1,2,3,4],'test2':[2,3,4,5]}
x = lambda a:[a[0],*a[1]]; print([x(i) for i in my_dict.items()])
#[['test1', 1, 2, 3, 4], ['test2', 2, 3, 4, 5]]

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM