Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simplify this mass of similar ifs

Tags:

python

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.

like image 443
Richard Knop Avatar asked Jul 05 '12 15:07

Richard Knop


2 Answers

for key, value in profile.iteritems():
    setattr(self, key, value)

Should do what you want

like image 154
Jakob Bowyer Avatar answered Sep 23 '22 20:09

Jakob Bowyer


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])
like image 27
Andrew Clark Avatar answered Sep 21 '22 20:09

Andrew Clark