Unpack list of dictionaries python

You can iterate over key, value pair of a dictionary like this:-

for k, v in dic.items[]:
    print[k, v]

what above code does is to first convert dictionary into a list of tuples which are then unpacked one by one while iterating into k, v just like:-

k, v = [k, v] # Tuple unpacking.

Now in your case, Consider this code:-

z = [x.items[] for x in lst]
print[z]

Output is

[dict_items[[['key1', 1]]], dict_items[[['key2', 2]]], dict_items[[['key3', 3]]]] 

i.e a list of lists of tuple.

So, Let us rewrite your code as :-

for k, v in z:
    print[k, v]

Where z is a list of lists of tuple. At each iteration, it picks up a list[which contains only one element] from the parent list and then it tries:-

k, v = [[key, value]] # a list of only one tuple to be unpacked against two variables and hence the failure.

I hope this was helpful.

Table of Contents

  • Dictionaries in Python
  • How to Unpack Dictionary in Python
    • Using the Unpack Operator [**] to Unpack Dictionary in Python
    • Using the for Loop to Unpack Dictionary in Python
    • Using the iteritems[] Function to Unpack Dictionary in Python
    • Using the items[] Function to Unpack Dictionary in Python
    • Using the keys and values Functions to Unpack Dictionary in Python
  • Conclusion
    • Was this post helpful?

In this article, we will see how to unpack dictionary in Python.

Dictionaries in Python

A dictionary is one of the fundamental data structures of Python. It stores its elements as key-value pairs and has evolved with time. In recent versions of Python, dictionaries use hash functions which make accessing values from keys a fast process and are also known to retain the order of elements.

Python uses the dict class that represents dictionaries as the base for many other objects so many operations are possible with them. We can unpack dictionaries as well.

Unpacking a dictionary means unloading and printing the key-value pairs or loading them in other objects like a tuple or a list. We also unpack a dictionary while sending their values to a function or when we are merging two dictionaries.

For this, we have the unpack operator in Python and loads of various functions that can be utilized.

We will now discuss different ways how to unpack dictionary in Python.

Using the Unpack Operator [**] to Unpack Dictionary in Python

The ** operator is used to pack and unpack dictionary in Python and is useful for sending them to a function. This will be made more clear with an example.

d={'k1':10,'k2':20,'k3':30}

def fun[k1,k2,k3]:

    print[k1,k2,k3]

fun[**d]    

Output:

10 20 30

In the above example, we have a function that accepts three arguments. We pass these three arguments by packing them in a dictionary using the ** operator.

We can use the ** to unpack dictionaries and merge them in a new dict object.

For example,

d={'k1':10,'k2':20,'k3':30}

new={'k0':0,**d}

print[new]    

Output:

{‘k0’: 0, ‘k1’: 10, ‘k2’: 20, ‘k3’: 30}

In the above example, we create a new dictionary by unpacking the contents of the previous dictionary in the new dictionary.

We also have an operator to unpack elements from the list. We can use this operator for dictionaries after converting them to a list of key-value pairs. We will discuss the methods to convert a dictionary to a list of key-value pairs as tuples below and unpack the elements using this operator.

Using the for Loop to Unpack Dictionary in Python

Dictionaries are iterable in Python. We can use the for loop to iterate by a dictionary and print its contents.

While iterating through a dictionary, we use its keys. We will then use the keys to access the value at every iteration and display them both.

See the following example.

d={'k1':10,'k2':20,'k3':30}

forkind:

    v =d[k]

    print['Key',k,'Value',v]    

Output:

Key k1 Value 10
Key k2 Value 20
Key k3 Value 30

In every iteration, we use the k variable to access the value at the given iteration and display them both.

We can also append them to a list of tuples. For this, we will create an empty list and append the key-value pairs as a tuple in every iteration.

For example,

d={'k1':10,'k2':20,'k3':30}

lst=[]

forkin d:

    v=d[k]

    lst.append[[k,v]]

print[lst]    

Output:

[[‘k1’, 10], [‘k2’, 20], [‘k3’, 30]]

In the above example, we first created an empty list lst and then went on to append the key-value pairs as a tuple using the append[] function.

After creating the list, we can unpack the elements using the unpack operator[*] operator discussed previously.

See the code below.

d={'k1':10,'k2':20,'k3':30}

lst=[]

forkin d:

    v=d[k]

    lst.append[[k,v]]

print[*lst]    

Output:

[‘k1’, 10] [‘k2’, 20] [‘k3’, 30]

Using the iteritems[] Function to Unpack Dictionary in Python

The iteritems[] function was available in Python 2 and it would return the key-value pairs of the dictionary in a view object.

We can use it to unpack dictionary in Python.

For example,

d={'k1':10,'k2':20,'k3':30}

lst=d.iteritems[]

print list[lst]    

Output:

[[‘k3’, 30], [‘k2’, 20], [‘k1’, 10]]

This function was replaced by the items[] function in Python 3.

Using the items[] Function to Unpack Dictionary in Python

The items[] function replaced the iteritems[] function in Python 3 and returns a better view object of the dictionary backed by the dict class. This function returns an object of type dict_items.

We can use the unpack operator [*] for lists with this object.

For example,

d={'k1':10,'k2':20,'k3':30}

lst=d.items[]

print[*lst]

Output:

[‘k1’, 10] [‘k2’, 20] [‘k3’, 30]

In the above example, we can observe the type of object returned by the items[] function is similar to a list but is backed by the dict class.

This function is also available in Python 2. However, in Python 2, this method directly returns a list of the elements of the dictionary and not a view-object. Any changes made in the dictionary after the items[] function call will not be observed in the returned list in Python 2.

Using the keys and values Functions to Unpack Dictionary in Python

The keys[] and values[] function of the dict class return a view-like object of the keys and values of a dictionary respectively.

We can use these functions with the zip[] method to unpack dictionary in Python.

See the code below.

d={'k1':10,'k2':20,'k3':30}

k=d.keys[]

v= d.values[]

lst  =list[zip[k,v]]

print[*lst]    

Output:

[‘k1’, 10] [‘k2’, 20] [‘k3’, 30]

In the above example,

  • The zip[] method combines the corresponding elements at each position in the view objects.
  • This object is converted to a list using the list[] function.
  • Elements are unpacked from this list using the unpack operator.

Conclusion

To conclude, in this article we discussed dictionaries and how to unpack dictionary in Python. We started by discussing dictionaries and unpack operations in Python. We can use the unpack operators with dictionaries in Python. The ** is directly used for packing and sending a dictionary as a function argument. We can also use this to unpack and merge dictionaries. We also have the unpack operator [*] operator that can unpack elements from lists or tuples. To use this, we convert the dictionary to a list of tuples and unpack the elements from this list. Several functions can be used to convert a dictionary to a list and then unpack them.

That’s all about how to unpack dictionary in Python.

How do I unpack a dictionary in Python?

The ** operator is used to pack and unpack dictionary in Python and is useful for sending them to a function. This will be made more clear with an example.

What is unpacking in Python?

Introduction. Unpacking in Python refers to an operation that consists of assigning an iterable of values to a tuple [or list ] of variables in a single assignment statement. As a complement, the term packing can be used when we collect several values in a single variable using the iterable unpacking operator, * .

How do you iterate a dictionary?

There are multiple ways to iterate over a dictionary in Python..
Access key using the build .keys[].
Access key without using a key[].
Iterate through all values using .values[].
Iterate through all key, and value pairs using items[].
Access both key and value without using items[].
Print items in Key-Value in pair..

How do I remove a dictionary from a list in Python?

Let's discuss certain ways in which this task can be performed..
Method #1 : Using del + loop. ... .
Method #2 : Using list comprehension. ... .
Method #3 : Using filter[] + lambda..

Chủ Đề