Home > Net >  Concise way to represent a list of dictionaries containing the same keys
Concise way to represent a list of dictionaries containing the same keys

Time:01-13

I have a list of dictionaries containing the same keys but different values. The values for key "A" are stored into a variable called animals_k. Given this, I was wondering if there was a more concise way to represent the following:

animals_k = ['tiger', 'elephant', 'cow', 'goat']
animal_class = [{"A":"tiger", "B": 0, "C":20, "D":4},
                {"A":"elephant", "B": 60, "C":8, "D":9},
                {"A":"cow", "B": 0, "C":34, "D":12},
                {"A":"goat", "B": 43, "C":43, "D":44}]

CodePudding user response:

You can create a dictionary containing a list of values for each key instead.

{
    "A": ["tiger", "elephant", ...],
    "B": [0, 60, ...],
    ...
}

CodePudding user response:

{
    "tiger": {
        "B": 60,
        "C": 0,
    },
    "dog": {
        "B": 100,
        "C": 12
    }
}
  •  Tags:  
  • Related