TransWikia.com

How to create a new python dictionary from loop results without overwrite

Stack Overflow Asked by Anderson Soares on July 29, 2020

I get stuck when I try to create a new dictionary with the result from each file.
Basically I have a bunch of files which I’m reading it using glob and json, so I managed to get the value from each file and it’s working fine, it’s displaying all files content with the different informations which is the expected and it’s good.

But now I’m looking about how to create a new dictionary new_dictonary = {} #in my code using the variable I’ve got get_hostname, get_fs_type, get_uptime without overwrite the new dictionary, below is my code.

import json
import glob
    
test_inventory = glob.glob('inventory/facts_am4/*')
new_dictonary = {}
for files in test_inventory:
    with open(files, 'r') as jsonfile:
        myfile = json.load(jsonfile)
        get_hostname = myfile['ansible_facts']['facter_networking']['fqdn']
        get_fs_type = myfile['ansible_facts']['facter_filesystems']
        get_uptime = myfile['ansible_facts']['facter_system_uptime']['uptime']
        print('Hostname: ' + get_hostname)
        print('FS Type:' + get_fs_type)
        print('Uptime:' + get_uptime)
        #Here I need something which you grab the variables and create a new dictionary.
        #Without overwrite.

I really tried a lot of stuffs, I’m learning Python and I came here to kindly request you help.

One Answer

You can either:

  1. make a list of dictionaries, and add a new one to it for each file, or
  2. make a nested dictionary, where each "info-dict" is keyed by the filename.

Using a list:

data_list = []
for filename in test_inventory:
    with open(filename, 'r') as file_obj:
        # read the data
        data = {'Hostname': get_hostname, 
                'FS Type': get_fs_type,
                'Uptime': get_uptime}
        data_list.append(data)
# Now data_list has a list of all your data, accessible as data_list[0], [1], etc.. 

Using a dictionary:

data_dict = {}
for filename in test_inventory:
    with open(filename, 'r') as file_obj:
        # as above
        data_dict[filename] = data
# Now data_dict has each file's data accessible as data_dict[filename]

Answered by tzaman on July 29, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP