简体   繁体   English

用单行for循环将dict项目附加到列表

[英]Append dict items to a list with a single line for loop

I have a list 我有一个清单

lst = []

I have dict entries 我有字典条目

a= {'a':1,'b':2}

I wish to write a for loop in a comprehension manner filling the list. 我希望以一种理解的方式编写一个for循环来填充列表。 What I have tried is 我试过的是

lst.append(k,v) for (k,v) in a.items()

I need to then update the dict as 然后我需要将字典更新为

a = {'c':3, 'd':4}

Then again update the list lst . 然后再次更新列表lst

Which adds the tuples as [('a',1)('b',2)('c',3)('d',4)] What is the right way to iterate through a dict and fill the list? 哪个将元组添加为[('a',1)('b',2)('c',3)('d',4)]迭代字典并填充列表的正确方法是什么?

This is what the syntax for a list comprehension is and should do what you're looking for: 这是列表推导的语法,应该可以满足您的需求:

lst = [(k,v) for k,v in a.items()]

In general list comprehension works like this: 通常, 列表理解是这样的:

someList = [doSomething(x) for x in somethingYouCanIterate]

OUTPUT OUTPUT

>>> lst
[('a', 1), ('b', 2)]

PS Apart from the question asked, you can also get what you're trying to do without list comprehension by simply calling : PS除了提出问题外,您还可以通过简单地调用以下命令来获得想要的操作而无需列表理解:

lst = a.items()

this will again give you a list of tuples of (key, value) pairs of the dictionary items. 这将再次为您提供字典项的(key, value)对的元组列表。

EDIT 编辑

After your updated question, since you're updating the dictionary and want the key value pairs in a list, you should do it like: 在更新问题之后,由于您要更新字典并希望将键值对放在列表中,因此您应该这样做:

a= {'a':1,'b':2}
oldA = a.copy()
#after performing some operation
a = {'c':3, 'd':4}
oldA.update(a)
# when all your updates on a is done
lst = oldA.items() #or [(k,v) for k,v in oldA.items()]
# or instead of updating a and maintaining a copy
# you can simply update it like : a.update({'c':3, 'd':4}) instead of a = {'c':3, 'd':4}

One approach is: 一种方法是:

a = {"a" : 1, "b" : 2}

lst = [(k, a[k]) for k in a]

a = {"c" : 3, "d" : 4}

lst += [(k, a[k]) for k in a]

Where the contents of lst are [('a', 1), ('b', 2), ('c', 3), ('d', 4)] . 其中lst的内容为[('a', 1), ('b', 2), ('c', 3), ('d', 4)]

Alternatively, using the dict class' .items() function to accomplish the same: 或者,使用dict类的.items()函数完成相同的操作:

a = {"a" : 1, "b" : 2}

lst = [b for b in a.items()]

a = {"c" : 3, "d" : 4}

lst += [b for b in a.items()]

There are many valid ways to achieve this. 有许多有效的方法可以实现此目的。 The most easy route is using 最简单的路线是使用

a = {"a" : 1, "b" : 2}
lst = list(a.items())

Alternatives include using the zip function, list comprehension etc. 替代方法包括使用zip功能,列表理解等。

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

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