简体   繁体   中英

Printing values from dictionary in specific form

I have a dictionary with keys relating to various reactions and their data ie. exponentn, comment etc. I want to search and print a list of reactions concerning the atom 'BR'. My code currently prints all reactions for 'BR' and the data in random order. I am not sure which data corresponds to which reaction.

I've had a go at trying to use the repr function to output the data as follows but I'm not having much luck:
reactionName : exponentn comment
I found another question which I tried to replicate but was not able to do so; printing values and keys from a dictionary in a specific format (python) .

class SourceNotDefinedException(Exception):
    def __init__(self, message):
        super(SourceNotDefinedException, self).__init__(message)

class tvorechoObject(object):
    """The class stores a pair of objects, "tv" objects, and "echo" objects. They are accessed simply by doing .tv, or .echo. If it does not exist, it will fall back to the other variable. If neither are present, it returns None."""
    def __init__(self, echo=None, tv=None):
        self.tv = tv
        self.echo = echo

    def __repr__(self):
        return str({"echo": self.echo, "tv": self.tv}) # Returns the respective strings

    def __getattribute__(self, item):
    """Altered __getattribute__() function to return the alternative of .echo / .tv if the requested attribute is None."""

        if item in ["echo", "tv"]:    
            if object.__getattribute__(self,"echo") is None: # Echo data not present
                return object.__getattribute__(self,"tv") # Select TV data
        elif object.__getattribute__(self,"tv") is None: # TV data not present
            return object.__getattribute__(self,"echo") # Select Echo data
        else:
            return object.__getattribute__(self,item) # Return all data

    else:
        return object.__getattribute__(self,item) # Return all data


class Reaction(object):
    def __init__(self, inputLine, sourceType=None):
        #self.reactionName = QVTorQPObject()
        self.exponentn = QVTorQPObject()
        self.comment = QVTorQPObject()
        self.readIn(inputLine, sourceType=sourceType)

        products, reactants = self.reactionName.split(">")
        self.products = [product.strip() for product in products.split("+")]
        self.reactants = [reactant.strip() for reactant in reactants.split("+")]


    def readIn(self, inputLine, sourceType=None):
        if sourceType == "echo": # Parsed reaction line for combined format

            echoPart           = inputLine.split("|")[0]    
            reactionName     = inputLine.split(":")[0].strip()
            exponentn        = echoPart.split("[")[1].split("]")[0].strip() # inputLine.split("[")[1].split("]")[0].strip()
            comment          = "%".join(echoPart.split("%")[1:]).strip() # "%".join(inputLine.split("%")[1:]).strip()

            # Store the objects
            self.reactionName = reactionName
            self.exponentn.echo = exponentn
            self.comment.echo = comment

        elif sourceType == "tv": # Parsed reaction line for combined format

            tvPart          = inputLine.split("|")[1]
            reactionName     = inputLine.split(":")[0].strip()
            comment          = "%".join(tvPart.split("!")[1:]).strip() # "%".join(inputLine.split("!")[1:]).strip()

            # Store the objects
            self.reactionName = reactionName
            self.comment.tv = comment


        elif sourceType.lower() == "unified":

            reaction = inputLine.split(":")[0]
            echoInput, tvInput = ":".join(inputLine.split(":")[1:]).split("|")

            echoInput = reaction + ":" + echoInput
            tvInput = reaction + ":" + tvInput

            if "Not present in TV" not in tvInput:
                self.readIn(inputLine, sourceType="tv")

            if "Not present in Echo" not in echoInput:
                self.readIn(inputLine, sourceType="echo")

        else:
            raise SourceNotDefinedException("'%s' is not a valid 'sourceType'" % sourceType) # Otherwise print

    def __repr__(self):
        return str({"reactionName": self.reactionName, "exponentn": self.exponentn, "comment": self.comment, })
        return str(self.reactionName) # Returns all relevant reactions


        keykeyDict = {}
        for key in reactionDict.keys():
            keykeyDict[key] = key

        formatString = "{reactionName:<40s} {comment:<10s}" # TV format
        formatString = "{reactionName:<40s} {exponentn:<10s} {comment:<10s}" # Echo format 
        return formatString.format(**keykeyDict)
        return formatString.format(**reactionDict)


    def toDict(self, priority="tv"):
        """Returns a dictionary of all the variables, in the form {"comment":<>, "exponentn":<>, ...}. Design used is to be passed into the echo and tv style line format statements."""
        if priority in ["echo", "tv"                # Creating the dictionary by a large, horrible, list comprehension, to avoid even more repeated text
            return dict([("reactionName", self.reactionName)] + [(attributeName, self.__getattribute__(attributeName).__getattribute__(priority))
               for attributeName in ["exponentn", "comment"]])

            else:
                raise SourceNotDefinedException("{0} source type not recognised.".format(priority)) # Otherwise print 

def find_allReactions(allReactions, reactant_set):
    """
    reactant_set is the set of reactants that you want to grab all reactions which are relevant allReactions is just the set of reactions you're considering. Need to repeatedly loop through all reactions. If the current reaction only contains reactants in the reactant_set, then add all its products to the reactant set. Repeat this until reactant_set does not get larger.
    """

    reactant_set = set(reactant_set) # this means that we can pass a list, but it will always be treated as a set.
    #Initialise the list of reactions that we'll eventually return
    relevant_reactions = []
    previous_reactant_count = None

    while len(reactant_set) != previous_reactant_count:
        previous_reactant_count = len(reactant_set)

    for reaction in allReactions:
        if set(reaction.reactants).issubset(reactant_set):
            relevant_reactions.append(reaction)
            reactant_set = reactant_set.union(set(reaction.products))

    return relevant_reactions

print find_allReactions(allReactions, ["BR"])

Current output:

'{'exponentn': {'tv': '0', 'echo': '0'}, 'comment': {'tv': 'BR-NOT USED', 'echo': 'BR-NOT USED'},'reactionName': 'E + BR > BR* + E', {'exponentn': {'qvt': '0', 'qp': '0'}, 'comment': {'qvt': 'BR+ -RECOMBINATION', 'qp': 'BR+ -RECOMBINATION'},'reactionName': 'E + BR* > BR* + E'

Desired output:
reactionName exponentn comment
E + BR > BR* + E 0 BR+ -RECOMBINATION

E + BR* > BR* + E 0 BR-NOT USED

如果您的数据按特定顺序添加到字典中,并且您想要保留该顺序,则需要使用collections.OrderedDict

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