Explicitness vs. DRY - which way is more pythons?

I need a wast dictionary, it displays mostly typical values, as well as some unique ones. The 1st way to get this definition of one flat "explicit" dictionary literal is:

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

2nd - "DRY" set of typical lists and a dictionary of special offers:

 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 the key-value relationship is much more variable (the values โ€‹โ€‹of some keys may change) in my case than in this example.

How would you prefer and why? In your opinion, which one is more pythons?

+4
source share
2 answers

My answer would be to add your data structures:

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

And if you should have it in the first format, understanding the dictionary will do the job well:

 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 have to do a lot of complicated manipulations, perhaps create a class of musicians to give yourself more freedom.

+9
source

For a short list of musicians, the first option is likely to be the best. If you have fairly large lists, I would take the second option. There is nothing incomprehensible in this, it reduces the risk of typos (which is very likely if the dict becomes big), and also organizes musicians in visually different lists.

+2
source

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


All Articles