简体   繁体   English

从字典以特定格式打印值

[英]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'. exponentn,评论等。我想搜索和打印有关原子'BR'的反应列表。 My code currently prints all reactions for 'BR' and the data in random order. 我的代码当前以随机顺序打印“ BR”的所有反应和数据。 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: 我曾尝试使用repr函数来输出数据,如下所示,但运气不佳:
reactionName : exponentn comment reactionName:exponentn评论
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) . 从字典以特定格式(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 reactionName指数注释
E + BR > BR* + E 0 BR+ -RECOMBINATION E + BR> BR * + E 0 BR +-重组

E + BR* > BR* + E 0 BR-NOT USED E + BR *> BR * + E 0不使用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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