简体   繁体   中英

Iterating over a dictionary while iterating a dictionary list in Python

I am writing a program and need to use this function to add Dependencies to an xml file. This code works, but I would like to ask if there is a more pythonic way to do so.

The part I believe I am doing in a non-pythonic way is the nested for loop. Is there a better way to iterate a list of dictionaries and each value?

def add_Dependencies(self):
        """ Adds the dependencies in a feature using dictionaries. When
            a feature is loaded, its dependencies are added to 
            dictionaries. Three for each type of software that the 
            dependencies are categorized as."""

        dependency_dict_list = [
            self.os_dict, self.visual_dict, self.audio_dict
            ]   

        dependencies = self.dependencies
        for dictionary in dependency_dict_list:                                                
            for feature, software in dictionary.items():                                            
                if all(dependency.text != feature for dependency in dependencies):
                    etree.SubElement(dependencies,"Dependency", Software = software).text = feature  

Honestly, nothing wrong with that at all. I put this together if you'd be interested it should be a little faster and is a tad less verbose. I cut out the nested for loop and flipped the all to an any (it reads a little cleaner to me, but that's really just taste).

all_dependencies = dict(self.os_dist, **self.visual_dict)
all_dependencies.update(self.audio_dict)

for feature, software in dictionary.items():
    if not any(dependency.text == feature for dependency in dependencies):
        etree.SubElement(dependencies,"Dependency", Software = software).text = feature

You can use collections.ChainMap to merge your three dictionaries into a single dictionary-like mapping. Or, since you don't care about the values, you could merge their keys into a set

It's not very important to use this to avoid the nested loops. Nested loops can be perfectly Pythonic, though you might want to factor some inner bits out into functions if the nesting gets too deep.

The real reason you might want to use a ChainMap or set here is to avoid the O(N**2) runtime complexity of searching your XML tree to eliminate duplicate dependencies. That they also eliminate a level of nesting is a minor side benefit.

Try something like this:

new_dependencies = (set(self.os_dict).union(self.visual_dict, self.audio_dict) -
                    set(dependency.text for dependency in self.dependencies))

for feature in new_dependencies:
   etree.SubElement(self.dependencies,"Dependency", Software = software).text = feature 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM