以特定形式打印字典中的值

时间:2015-01-07 19:30:27

标签: python dictionary key

我有一本字典,其中包含与各种反应及其数据相关的键。 exponentn,comment等我想搜索并打印有关原子'BR'的反应列表。我的代码目前以随机顺序打印“BR”的所有反应和数据。我不确定哪个数据对应哪个反应。

我已经尝试使用repr函数输出数据如下,但我没有太多运气:
reactionName:exponentn comment
我发现了另一个我试过的问题复制但无法复制; 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"])

当前输出:

'{'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'

所需输出:
reactionName exponentn评论
E + BR&gt; BR * + E 0 BR + -RECOMBINATION

E + BR *&gt; BR * + E 0 BR-NOT USED

1 个答案:

答案 0 :(得分:0)

如果您的数据按特定顺序添加到dict中,并且您希望保留该顺序,则collections.OrderedDict就是您要查找的内容。