There is a large dictionary in which entries are dictionaries of this type:

"Smth": { "name": "Text", "enemies": [ "enemy1", "enemy2", "enemy3" ], "friends": [ "friend1", "friend2", "friend3" ] }, 

We need to give weight to all values ​​from the enemies and friends , which will always be extracted along with this weight. For example, enemy1 has a weight of 0.4 , and friend3 has a weight of 0.8 . For each value the weight will be specified manually.

How to do it better? So far, I have done only this method:

  "enemies": [ ["enemy1", 0.4], ["enemy2", 0.3], ["enemy3", 0.7] ] 

Is it a better option? Speed ​​is in priority. Thank.

UPD: We need just such a format, because these dictionaries will be written to a .json file.

  • The tuple may be faster: "enemies": [("enemy1", 0.4), ("enemy2", 0.3)] - Vladimir Gamalyan
  • @VladimirGamalian Yes, about the tuple, this would not seem to be an option, since these dictionaries will then be stored in a json file. If I'm not mistaken, there are no tuples, only lists. Forgot to mention. - Newbie
  • If speed was not a priority, I would have made enemy1 dictionary with a weight field, which would give the opportunity to add enemies and other properties later. - Vladimir Gamalyan
  • nothing prevents you from having a beautiful class that reads code generates, and at the same time having a serialization of objects of this class in json. For example, WeigthedItem = namedtuple('WeightedItem', 'id weight') , and when saved as json: default=lambda o: list(o) if isinstance(o, WeightedItem) else json.Encoder().default(o) . And so "Better" is subjective: if the code does what it wants, simple, readable and works at a speed sufficient in your case, then it is better to try to improve it in other places. Explicitly indicate a specific problem with the code (readability, consumed memory, speed). - jfs

1 answer 1

collections - High-performance container datatypes: namedtuple

 enemy = namedtuple('Item', ['name', 'weight']) enemies = [ enemy('enemy1', weight=.4), enemy('enemy2', .3), enemy('enemy3', .7) ] e = enemies[2] print(e) print(e.weight) name, weight = e print(name, e[1]) 

out:

 Item(name='enemy3', weight=0.7) 0.7 enemy3 0.7