Как преобразовать объект в словарь python
Перейти к содержимому

Как преобразовать объект в словарь python

  • автор:

Represent Python Class As Dictionary

Alexandre Paes

Represent a class by a dictionary: the class attributes became the dictionary keys and the attributes values the dictionary values.

Solution

Explanation

In Python, when a class is evaluated the method __repr__ is called and it can only return the string type. If you try to return anything different an exception is raised:

But Dictionary(dict) is a built-in type/class and it is represented by a dictionary (obviously)…

The solution consisted in:

1 — Make a class inherit from the dict class

2 — Overwrite the __repr__ method setting the dictionary keys and values with the __setitem__ method and return the super().__repr__, which can return dicts.

I couldn’t make my class work like a dict without inheriting from it, if you can please share your solution in the comments ;).

Как преобразовать список в словарь в Python

Существует множество способов интерпретации данных в списке, как ключей и значений, и преобразования этого списка в словарь.

  • [ключ_1, значение_1, ключ_2, значение_2,…] – Ключ: пары значений как непрерывные элементы списка.
  • [key_1, key_2, â € ¦], [value_1, value_2, â € ¦] â € «Ключи находятся в одном списке, а значения – в другом списке.
  • [(ключ_1, значение_1), (ключ_2, значение_2),…] Ключ: пары значений как кортежи, и эти кортежи являются элементами списка.
  • Преобразование списка в словарь с элементом списка в качестве ключа и индексом в качестве значения.
  • Преобразование списка в словарь с элементом списка в качестве ключа, и значением по умолчанию.

В этом руководстве мы узнаем, как преобразовать эти форматы списков в словарь с помощью хорошо подробных примеров программ.

Пример 1

В этом примере мы преобразуем список формата [key_1, value_1, key_2, value_2, â € ¦] в словарь .

Мы будем использовать понимание словаря, чтобы преобразовать этот тип списка в словарь.

Пример 2: преобразование списка ключей

В этом примере мы преобразуем список формата [(key_1, value_1), (key_2, value_2), â € ¦] в словарь .

Мы будем использовать понимание словаря, чтобы преобразовать эти списки ключей и значений в словарь.

Пример 3: преобразование списка кортежей

В этом примере мы преобразуем список формата [(key_1, value_1), (key_2, value_2), â € ¦] в словарь .

Мы будем использовать понимание словаря для преобразования списка кортежей в словарь.

Пример 4: с индексом

В этом примере мы преобразуем список формата [key_1, key_2, â € ¦] в словарь .

Пример 5: значение по умолчанию

В этом примере мы преобразуем список формата [key_1, key_2, â € ¦] в словарь .

Python object and dictionary convertion

When programing in Python, sometimes you want to convert an object to dictionary and vise versal. In this article, I share my expericences to do that.

Convert from class to dictionary

When you want to convert a class to dictionary just define class override from object (this is important) and then call method __dict__ :

Convert from dictionary to class

In contrast, if you want to convert a dictionary to object, use this method. I did not invent this method, it is borrowed from stackoverflow.com)

I change above methods like bellow to get recusive convertion dictionary:

In python, how do I cast a class object to a dict

What do I need to define for this to work? I tried substituting both __dict__ and dict for __what_goes_here__ , but dict(w) resulted in a TypeError: Wharrgarbl object is not iterable in both cases. I don’t think simply making the class iterable will solve the problem. I also attempted many googles with as many different wordings of «python cast object to dict» as I could think of but couldn’t find anything relevant :<

Also! Notice how calling w.__dict__ won’t do what I want because it’s going to contain w.version and w.sum . I want to customize the cast to dict in the same way that I can customize the cast to int by using def int(self) .

I know that I could just do something like this

But I am assuming there is a pythonic way to make dict(w) work since it is the same type of thing as int(w) or str(w) . If there isn’t a more pythonic way, that’s fine too, just figured I’d ask. Oh! I guess since it matters, this is for python 2.7, but super bonus points for a 2.4 old and busted solution as well.

There is another question Overloading __dict__() on python class that is similar to this one but may be different enough to warrant this not being a duplicate. I believe that OP is asking how to cast all the data in his class objects as dictionaries. I’m looking for a more customized approach in that I don’t want everything in __dict__ included in the dictionary returned by dict() . Something like public vs private variables may suffice to explain what I’m looking for. The objects will be storing some values used in calculations and such that I don’t need/want to show up in the resulting dictionaries.

UPDATE: I’ve chosen to go with the asdict route suggested but it was a tough choice selecting what I wanted to be the answer to the question. Both @RickTeachey and @jpmc26 provided the answer I’m going to roll with but the former had more info and options and landed on the same result as well and was upvoted more so I went with it. Upvotes all around though and thanks for the help. I’ve lurked long and hard on stackoverflow and I’m trying to get my toes in the water more.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *