· 1 min read

Destructuring Dictionaries in Python

Here is a quick and dirty way to destructure dictionaries in [Python]

d = {'a':'Apple', 'b':'Banana','c':'Carrot'}
a,b,c = [d[k] for k in ('a', 'b','c')]

a == 'Apple'
b == 'Banana'
c == 'Carrot'

6 comments

  • Amit

    Another option:

    a, b, c = d.values()

  • Sopof

    from operator import itemgetter
    data = {'a':'apple','b':'ball'}
    a ,b = itemgetter('a','b')(data)

  • Sitnarf

    @Amit key order is not guaranteed, you can end up having values in wrong variables

  • Dontwant

    Key order is guaranteed in recent python versions

  • Danetrata

    Key order is guaranteed in recent python versions
    ...
    Is there a source for this? That would be a big change.

  • Tangentsecantcosinesine

    "Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6."

Leave a comment