nina_dev
nina_dev

Reputation: 695

How can I extract keys within keys of a dictionary

I have the following structure:

mappings": {
"go": {
"_ttl": {something goes here},
"symbol": {},
"associationType.keyword": {},
"go_genes": {},
"go_species.keyword": {},
"symbol.autocomplete": {},
"primaryId": {},
"href.keyword": {},
"name_key": {},
"symbol.sort": {},
"name_key.keyword": {},
"go_type.keyword": {},

Now, I am interested in extracting something like this:

mappings.go.-ttl
mappings.go.symbol
mappings.go.geo_genes
.....

Here is the code that I wrote, but it only gives me "go" and other nodes that are at similar position as go, which, are not shown at the picture. How can I modify it to get my desired outcome as described abode:

index = "site_index_stage"
elastic_url = "http://localhost:9200"
mapping_fields_request = "_mapping/field/*"
mapping_fields_url = "/".join([elastic_url, index, mapping_fields_request])
response = requests.get(mapping_fields_url)
print(response)
data = response.content.decode()
parsed_data = json.loads(data)
for key in parsed_data[index]['mappings']:
    print(key)

Upvotes: 0

Views: 32

Answers (1)

nina_dev
nina_dev

Reputation: 695

Here is how I did it, finally:

def nested_dict_iter(nested):
    for key, value in nested.items():
        # print((key,value))
        if type(value)==type({}):
            for x in value:
                output.write(key+'.'+x)
                output.write('\n')
nested_dict_iter(parsed_data[index]['mappings'])

Upvotes: 1

Related Questions