Search code examples
pythonlistdictionaryfor-loopdictionary-comprehension

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. 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.

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?


Solution

  • 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

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

    P.S. Apart from the question asked, you can also get what you're trying to do without list comprehension by simply calling :

    lst = a.items()
    

    this will again give you a list of tuples of (key, value) pairs of the dictionary items.

    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}