How to simplify this mass of similar ifs

I am trying to figure out how to simplify this piece of code. The logic for each if condition is basically the same, so I want to get rid of the duplicate ifs:

if "video_codec" in profile: self.video_codec = profile["video_codec"] if "resolution_width" in profile: self.resolution_width = profile["resolution_width"] if "resolution_height" in profile: self.resolution_height = profile["resolution_height"] if "ratio" in profile: self.ratio = profile["ratio"] if "video_bitrate" in profile: self.video_bitrate = profile["video_bitrate"] if "profile" in profile: self.profile = profile["profile"] if "audio_codec" in profile: self.audio_codec = profile["audio_codec"] if "audio_channels" in profile: self.audio_channels = profile["audio_channels"] if "audio_bitrate" in profile: self.audio_bitrate = profile["audio_bitrate"] 

Hope this can be done in 3-4 lines instead of my 18 lines.

+6
source share
2 answers

If you want to copy all key / value pairs from profile to attributes in self , you can use the following:

 self.__dict__.update(profile) 

If there are some elements in the profile that you do not want to copy, you can use the following:

 for attr in ("video_codec", "resolution_width", "resolution_height", "video_bitrate", "ratio", "profile", "audio_codec", "audio_channels", "audio_bitrate"): if attr in profile: setattr(self, attr, profile[attr]) 
+7
source
 for key, value in profile.iteritems(): setattr(self, key, value) 

Gotta do what you want

+10
source

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


All Articles