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.
You can either:
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
3 Asked on December 11, 2021 by kimor
1 Asked on December 11, 2021 by vilicvane
2 Asked on December 11, 2021 by schalk-joubert
1 Asked on December 11, 2021 by wytex-system
1 Asked on December 11, 2021 by thribhuwan
1 Asked on December 11, 2021 by stephen-agwu
2 Asked on December 11, 2021 by peer
1 Asked on December 11, 2021 by ilovesomething23
2 Asked on December 11, 2021 by alloylo
1 Asked on December 11, 2021 by elgate
0 Asked on December 11, 2021 by aannaa
0 Asked on December 11, 2021 by pprovins
1 Asked on December 11, 2021 by wis
0 Asked on December 11, 2021 by 1005hoon
1 Asked on December 9, 2021 by lfc-productions
2 Asked on December 9, 2021 by wayne2
Get help from others!
Recent Answers
Recent Questions
© 2023 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP