Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicitness vs. DRY - which way is more pythonic? [closed]

I need the wast dictionary, maps mostly on typical values, as well as some unique ones. 1st way to obtain it is defining one flat "explicit" dictionary literal:

musicians = {
    'ABBA': 'pop',
    'Avril Lavigne': 'pop',
    ...
    'Mikhail Krug': 'russian chanson',
    'The Rolling Stones': 'rock',
    ...
    'Zaz': 'jazz',
}

2nd - "DRY" bunch of typical lists and the dictionary of specials:

pop_musicians = [
    'ABBA',
    'Avril Lavigne',
    ...
]

rock_musicians = [...]

unusual_musicians = {
    'Mikhail Krug': 'russian chanson',
    'Zaz': 'jazz',
}

musicians = dict(
    [(m, 'pop') for m in pop_musicians] +
    [(m, 'rock') for m in rock_musicians] +
    unusual_musicians.items()
)

Suppose also key-value relations much more variable (values of certain keys are likely to change) in my case than in this example.

Which way would you prefer and why? In your opinion, which one is more pythonic?

like image 209
leventov Avatar asked Dec 20 '22 16:12

leventov


1 Answers

My answer would be to layer your data structures:

genres = {
    "rock": [
        "some rock band",
        "some other rock band",
    ],
    "pop": [
        "some pop star",
        "some pop group",
    ],
}

And if you have to have it in the first format, a dictionary comprehension will do the job nicely:

musicians = {musician: genre for genre, musicians in genres.items() for musician in musicians}

Will produce:

{'some other rock band': 'rock', 'some pop group': 'pop', 'some rock band': 'rock', 'some pop star': 'pop'}

Or, if you find yourself having to do a lot of complex manipulation, maybe make a musician class to give yourself more freedom.

like image 175
Gareth Latty Avatar answered Jan 21 '23 06:01

Gareth Latty