I'm new to learning python and i've learned to push a config file data into nested dict. how is it done vice versa? example fille would be like:
i need
dictonary = { 'section1': { 'name': 'abcd', 'language': 'python' }, 'section2': { 'name': 'aaaa', 'language': 'java' } }
into something like this
[section1]
name: abcd
language: python
[section2]
name: aaaa
language: java
This will work and here's why:
our_dict = {
'section1':{
'name':'abcd',
'language':'python'
},
'section2':{
'name':'aaaa',
'language':'java'
}
}
def dictFunc(dictionary):
ret = ''
for i in dictionary:
value = dictionary.get(i)
ret += '\n' + i + ':\n'
for j in value:
k = value.get(j)
ret += j + ':' + k + '\n'
return ret
print(dictFunc(our_dict))
First, we declare our_dict
. Then, we declare the function
dictFunc()
, with one argument
; the dictionary
. We make a variable
named ret
, which we will soon return
. We start by looping the dictionary
, and declaring the variable
value
. It's the dictionary
's second-place key
(ie {'name':'aaaa','language':'java'}
). We make sure to add the key
(ie section1) to ret
. We loop our second-place key
, or j
, to get j
and j's current key
, or k
(ie, name
.). Finally, we get j's current second-place key
, and link them together in ret
. We now return ret
.
You can use the module configparser .
import configparser
dictonary = {
'section1' : { 'name' : 'abcd' , 'language' : 'python' } ,
'section2' : { 'name' : 'aaaa' , 'language' : 'java' } }
config = configparser.RawConfigParser()
for section, pairs in dictonary.items():
config.add_section(section)
for k,v in pairs.items():
config.set(section, k, v)
with open('example.cfg', 'w') as configfile:
config.write(configfile)
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.