Pythonic alternative to (nested) dictionaries with the same keys?

I avoid dictionaries because almost half of their code is duplicated. I usually do this in nested dictionaries, where all sub-dictionaries contain the same keys, but different meanings.

I manually create a large parent dictionary, where each key contains a nested dictionary that will be used in external modules. Nested dictionaries use the same keys to determine configuration parameters. This usage is explicit and works, but it seems silly to repeat or copy / paste keys for each nested dictionary that I create manually. I'm not too concerned about optimizing memory or performance, just wondering if I should do this another, more Pythonic.

As a trivial example and template, you can often see:

people_dict = { "Charles Lindberg": {"address": "123 St.", "famous": True}, "Me": {"address": "456 St.", "famous": False} } >>>people_dict["Charles Lindberg"]["address"] "123 St." 

While the dictionary includes explicit code, it is tiresome and error prone to define nested dictionaries with duplicate keys. In this example, half of the nested dictionary is the code duplication code common to all nested dictionaries. I tried to use tuples to eliminate duplicate keys, but found that this leads to fragile code - any change in position (and not the dictionary key) fails. This also leads to the fact that the code is not explicit and difficult to follow.

 people_dict = { "Charles Lindberg": ("123 St.", True), "Me": ("456 St.", False), } >>>people_dict["Charles Lindberg"][0] "123 St." 

Instead, I write a class to encapsulate the same information: This successfully reduces duplicate code ...

 class Person(object): def __init__(self, address, famous=False): self.address = address self.famous = famous people_dict = [ "Charles Lindberg": Person("123 St.", famous=False), "Me": Person("456 St."), ] >>>people_dict["Charles Lindberg"].address "123 St." 

Creating a class seems a little redundant ... Standard data types seem too basic ...

I guess the best way to do this is in Python, without having to write your own class?

What is the best way to avoid code duplication when creating nested dictionaries using shared keys?

+6
source share
3 answers

It looks like you have a data matrix, since each "row" has the same keys (columns), so I would use a NumPy array:

 import numpy as np dtype = [('name', object), ('address', object), ('famous', bool)] people = np.array([ ("Charles Lindberg", "123 St.", True), ("Me", "456 St.", False), ], dtype) charlie = people[people['name'] == 'Charles Lindberg'][0] print charlie['address'] 

Or using Pandas, which is higher level:

 import pandas as pd people = pd.DataFrame(people_dict) print people['Charles Lindberg']['address'] 

This very easily loads your original dict-of-dicts people_dict directly into the matrix and gives you similar search functions.

+3
source

First, you can read the link above to get more information on nametuples: https://docs.python.org/2/library/collections.html#collections.namedtuple

NamedTuples can help you avoid code duplication. You can create namedtuple for the address and use it to determine.
I particularly prefer Object. OO has a better solution to this problem. You can create a method to export an object to a dict.

For a functional paradigm, it is better to use lists, an array, and a dict, because for this structure (maps, abbreviations, etc.) there are many methods / functions. If you do not pretend to use any functionality in your application, go to the OO (object-oriented) solution.

Relations Andre

0
source

If you want to use a dict where all values ​​are dicts with the same or similar keys, you can define a function that takes values ​​and returns one of the internal dicts.

 def hash(address, famous): return {"address": address, "famous": famous} people_dict = { "Charles Lindberg": hash("123 St.", true), "Me": hash("456 St.", false) } 
0
source

Source: https://habr.com/ru/post/977511/


All Articles