I am trying to figure out how to simplify this piece of code. The logic for every 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"]
I hope this can be done in 3-4 lines instead of my 18 lines.
for key, value in profile.iteritems():
setattr(self, key, value)
Should do what you want
If you just 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 items in profile
that you do not want to copy, then 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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With