Namedtuple vs Dictionary

 ̄綄美尐妖づ 提交于 2019-12-24 01:16:00

问题


So I'm programming a game and I need a datatype that can store a multitude of variables ranging from lists, tuples, strings and integers. I'm torn between using either dictionaries or namedtuples.

GameData = namedtuple('GameData', ['Stats', 'Inventory', 'Name', 'Health'])
current_game = GameData((20,10,55,3), ['Sword', 'Apple', 'Potion'], 'Arthur', 100)

GameData = {'Stats': (20,10,55,3), 'Inventory': ['Sword', 'Apple', 'Potion'], 'Name': 'Arthur', 'Health': 100}

You see, the biggest problem here is all of these values may change, so I need a mutable datatype, which is not the namedtuple. Looking in the docs, namedtuples appear to have ._replace(), so does that make it mutable?

I also like how namedtuples have a __repr__ method that prints in the name=value format. Also, the functionality of assigning separate __doc__ fields to each value in the namedtuple is very useful. Is there this functionality with dictionaries?


回答1:


Just use a class. The problem with dictionaries is that you don't know which keys to expect and your IDE won't be able to autocomplete for you. The problem with namedtuple is that is not mutable. With a custom class you get both readable attributes, mutable objects and a lot of flexibility. Some alternatives to consider:

  • Starting from Python 3.7 you could use the dataclasses module:

    from dataclasses import dataclass
    
    @dataclass
    class GameData:
        stats: tuple
        inventory: list
        name: str
        health: int
    
  • In case other Python versions, you could try attrs package:

    import attr
    
    @attr.s
    class GameData:
        stats = attr.ib()
        inventory = attr.ib()
        name = attr.ib()
        health = attr.ib()
    



回答2:


Looking in the docs, namedtuples appear to have ._replace(), so does that make it mutable?

No, as specified in the documentation, it creates a new namedtuple, with the value replaced.

If you want the data to be mutable, you better construct a class yourself.



来源:https://stackoverflow.com/questions/41613015/namedtuple-vs-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!