0
import json

data ='''
    {
   "names": {"first_boy" : "khaled"},
   "names": {"second_boy" : "waseem"}
    }
    '''
info = json.loads(data)
for line in info:
    print(info["names"])

I expected it to print the first_boy and the second_boy dictionary ,but it's printing

{'second_boy': 'waseem'}

sanster_23
  • 800
  • 10
  • 17
waseem hazem
  • 25
  • 1
  • 6

2 Answers2

4

Dicts in python can only support one of the same key. Similarly, most implementations of JSON do not allow duplicate keys. The way python handles this, when using json.loads() (or anything else that constructs a dict) is to simply use the most recent definition of any given key.

In this case, {"second_boy":"waseem"} overwrites {"first_boy":"khaled"}.

Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53
1

The problem here is that the key "names" exists 2 times. Maybe you can do this:

import json

data ='''
    {
   "names": {"first_boy" : "khaled",
             "second_boy" : "waseem"}
    }
    '''
info = json.loads(data)
for key, value in info['names'].items():
    print(key, value)
Kevin Müller
  • 722
  • 6
  • 18