1

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?

2
  • 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)? Commented Mar 23, 2018 at 4:40
  • 1
    Is it a json STRING or a json OBJECT (aka, dictionary)? Commented Mar 23, 2018 at 4:40

2 Answers 2

5

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'}]
Sign up to request clarification or add additional context in comments.

Comments

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'}]

4 Comments

Any chance you can explain what you did here?
I'd advise against using list comprehensions to generate side effects. You're on the right track, but use a loop instead.
(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)
Thanks for the feedback. No worries.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.