Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Destructure a `dict` of length one to assign its key and value to two variables in Python

I have a bunch of dictionaries with only one key-value pairs that are sometimes generated by one of the scripts I wrote, and I need to get rid of them.

To do this, I need to get the key and value of the dict. Minimal reproducible example to illustrate my intent:

d = {'a': 0}
assert len(d) == 1
k, v = list(d.items())[0]

Don’t know if this is a duplicate, but I can’t find an answer using Google.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there a simpler way to get k, v from d?

>Solution :

If you don’t need the dict anymore:

k, v = d.popitem()

If you do:

(k, v), = d.items()

Try it online!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading