-1

I'm building the dict by fetching values from the devices. I would like keep adding new dict into "c" by appending a new item. How can to append new dict within array:

dict1 = {
'a': 1,
'b': 2,
'c': [{'aa': 11, 'bb': 22}]}
newvalue = {'aa': 111, 'bb': 222}
dict1['c'] = dict1['c'] + newvalue

End results:
dict1 = {
'a': 1,
'b': 2,
'c': [{'aa': 11, 'bb': 22},{'aa': 111, 'bb': 222}}

How to append using forloop?

netkool
  • 45
  • 1
  • 11
  • 1
    `dict1['c'].append(newvalue)`…? – deceze May 14 '18 at 20:20
  • What you're doing already works. If you make a bunch of `newvalue` values inside a `for` loop, you can just use the exact same code you already have to add each of those values. – abarnert May 14 '18 at 20:21
  • would like to add newvalues into dict['c'], how can i append the newvalue – netkool May 14 '18 at 20:22
  • doesn't work. here i code I tired: ```for k, v in dict1['c'][0].iteritems(): dict1['c'].append(v) print dict1``` – netkool May 14 '18 at 20:22

2 Answers2

2

The trick to this question is understanding your object types.

Let's try finding the type of dict1['c'], as this is the one we're trying to add to:

print(type(dict1['c']))
<class 'list'>

While we're at it let's see what's inside this list:

print(type(dict1['c'][0]))
<class 'dict'>

So we have a list, and the first element of the list is a dictionary.

It looks like we want to add another dictionary to this list. But, wait, is the fact we're adding a dictionary at all relevant? Probably not, we know list can contain any number of objects.

So let's see how we can add to a list. A quick google gives us Difference between append vs. extend list methods in Python. So we need list.append. Let's try that:

dict1['c'].append(newvalue)

print(dict1)

{'a': 1,
 'b': 2,
 'c': [{'aa': 11, 'bb': 22},
       {'aa': 111, 'bb': 222}]}

Hey, presto! That's exactly what we were looking for.

jpp
  • 159,742
  • 34
  • 281
  • 339
  • Thank you JPP it was good: Question: for example: within a forloop I found a value and need to add to key: "aa", so I did >> `dict1['c'][0]["aa"] = 333` and `dict1['c'][0]["bb"] = 444` Now how to add those two into conituing array of dict? – netkool May 14 '18 at 20:34
  • @netkool, Sorry, it's not clear what you are doing. In your comment, you are **changing the value for dictionary keys** (specifically first dictionary) for keys `aa` and `bb` respectively. This has **nothing** to do with adding elements. – jpp May 14 '18 at 20:40
0

And to elaborate on jpp's superior answer, it does work in a for loop (the code below would usually have an index instead of simply 'newvalue').

newvalue = {'aa': 111, 'bb': 222}

dict1 = {
'a': 1,
'b': 2,
'c': [{'aa': 11, 'bb': 22}]}

for i in range(1):
    dict1['c'].append(newvalue)
print(dict1)

Result:

{'a': 1, 'b': 2, 'c': [{'aa': 11, 'bb': 22}, {'aa': 111, 'bb': 222}]}
goks
  • 1,196
  • 3
  • 18
  • 37