0

I have the below json, I want to add one more property:

[   {
        "A": 1,
        "B": "str"
    },
    {
        "A": 2,
        "B": "str2"
    },
    {
        "A": 3,
        "B": "str3"
    }
]

So I want something like this:

[   {
        "A": 1,
        "B": "str",
        "C": "X"
    },
    {
        "A": 2,
        "B": "str2",
        "C": "X"
    },
    {
        "A": 3,
        "B": "str3",
        "C": "X"
    }
]

What is the best way to do this?

cs95
  • 379,657
  • 97
  • 704
  • 746
Python
  • 11
  • 1
  • 4
  • 1
    1. Add the exact same key/val on each occasion, or different ones? 2. Modify existing dicts, or create new ones? 3. Do you have json (as written) or a dict (as shown)? – wim Mar 23 '18 at 04:40
  • 1
    Is it a json STRING or a json OBJECT (aka, dictionary)? – cs95 Mar 23 '18 at 04:40

2 Answers2

4

Loop through each dict obj in the list and add required key value pair that you want:

List Before

list1 = [       
   {
        "A": 1,
        "B": "str"
    },
    {
        "A": 2,
        "B": "str2"
    },
    {
        "A": 3,
        "B": "str3"
    }
]

The code

for l in list1:
    l['C'] = 'X'

print(list1)

List After i.e Output

[{'A': 1, 'B': 'str', 'C': 'X'}, {'A': 2, 'B': 'str2', 'C': 'X'}, {'A': 3, 'B': 'str3', 'C': 'X'}]
the.salman.a
  • 945
  • 8
  • 29
2
>>> j = [ { "A": 1, "B": "str" }, { "A": 2, "B": "str2" }, { "A": 3, "B": "str3" } ]
>>> [i.update({'C': 'X'}) for i in j]
>>> j
[{'A': 1, 'B': 'str', 'C': 'X'}, {'A': 2, 'B': 'str2', 'C': 'X'}, {'A': 3, 'B': 'str3', 'C': 'X'}]

Or, as per coldspeed's comment:

>>> for item in j:
...     item['C'] = 'X'  
... 
>>> j
[{'A': 1, 'B': 'str', 'C': 'X'}, {'A': 2, 'B': 'str2', 'C': 'X'}, {'A': 3, 'B': 'str3', 'C': 'X'}]
Carlo Mazzaferro
  • 838
  • 11
  • 21
  • 1
    Any chance you can explain what you did here? – Stephen Rauch Mar 23 '18 at 04:41
  • 5
    I'd advise against using list comprehensions to generate side effects. You're on the right track, but use a loop instead. – cs95 Mar 23 '18 at 04:41
  • (responding to your edit) an assignment to `i` will end up modifying `j` (print it out and see), because the `for` loop iterates over the references. In short, the `new_list` is not required. (also, I did not downvote) – cs95 Mar 23 '18 at 04:48
  • Thanks for the feedback. No worries. – Carlo Mazzaferro Mar 23 '18 at 04:54