简体   繁体   中英

Extract nested dictionary values in Python

I think I'm close but spinning in circles on this one. I have a dictionary in Python that has been imported from JSON. The raw data is too much to post here. The code works like I want and prints what I want, except it only returns the last value from the dictionary. How would I modify this to return all values and print exactly how it is shown here? Ultimately I want to take this data and add it to a database as one entry.

Code:

text = json.loads(content)

a = {}

def extract(DictIn, Dictout):
    for key, value in DictIn.iteritems():
        if isinstance(value, dict): 
            extract(value, Dictout)
        elif isinstance(value, list):
            for i in value:
                extract(i, Dictout)
        else:
            Dictout[key] = value

extract(text, a)

for k, v in a.iteritems():
    print k, ":", v

Result should look like the following, but have the other 40 or so entries. Currently the code only shows the last entry:

datetime : 2014-06-10T20:00:00-0600
date : 2014-06-10
href : http://xxxxxxxxxxxx.json
lng : -94.5554
id : 17551289
createdAt : 2013-07-30T12:18:56+0100
city : Kansas City, MO, US
billing : headline
totalEntries : 37
type : Concert
billingIndex : 1
status : ok
perPage : 50
setlistsHref : xxxxxxxxxxxx:51b7f46f-6c0f-46f2-9496-08c9ec2624d4/setlists.json
lat : 39.0763
displayName : Ben Folds
eventsHref : http://xxxxxxx.08c9ec2624d4/calendar.json
popularity : 0.0
uri : xxxxxxxxxxxxxxxxxx
mbid : xxxxxxxxxxx
onTourUntil : 2014-06-10
time : 20:00:00
page : 1

The problem is with your Dictout[key] = value

in Python Dictionary the keys are unique

Assume

_d = {1: 'one', 2: 'two'}

>>> print _d
{1: 'one', 2: 'two'}

>>> _d[1] = 'another one'
>>> print _d
{1: 'another one', 2: 'two'}

I guess in your for loop you are overwriting value of an existing key , that's why only your last entry is getting stored !.

Try changing your data structure, something like list of dictionaries , so that your output may look like,

my_out_list = [{1: 'one', 2: 'two'}, {1: 'another one', 2: 'two'}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM