How can I iterate between keys and values in a dictionary defined in INI file where both fields are strings?
Inside the config.ini file I have:
proxy : {'Brasil':'186.233.104.25:8080',
'Chile':'190.82.76.58:32570',
'Ecuador':'186.3.228.98:8080',
'venezuela':'190.121.227.174:3128',
'venezuela':'190.121.227.174:3128',
'Colombia':'191.102.83.146:80',
'Paraguay':'190.93.176.70:8080'}
and I try to access the dictionary like this:
def __init__(self, Cons):
config = configparser.ConfigParser()
config.read(testdir + '\config.ini')
self.proxy = config.get(Cons, 'proxy')
print(repr(self.proxy))
for pais, ip in proxy.items():
Pais = str(pais)
ip = str(ip)
But I have the error:
Exception has occurred: AttributeError 'str' object has no attribute 'items'
output ofprint(repr(self.proxy))
"{'Brasil':'186.233.104.25:8080',\n'Chile':'190.82.76.58:32570',\n'Ecuador':'186.3.228.98:8080',\n'venezuela':'190.121.227.174:3128',\n'venezuela':'190.121.227.174:3128',\n'Colombia':'191.102.83.146:80',\n'Paraguay':'190.93.176.70:8080'}"
By default
ConfigParser
it has only three methods that allow type conversion,getboolean
,getint
andgetfloat
. In order to correctly parse the dictionary, you need to specify with the help ofconverters
the constructor argument how we want the dictionary to be parsed.To do this, a dictionary is passed in which the key will be the name (which we then access through the method
getnombre()
and the key a callable that receives the string and returns the converted object. We can create the dictionary from the string usingast.literal_eval
.Starting for example from this config.ini :
to be able to access it:
Note that you can also use your own section for your dictionary data, which makes everything much simpler:
and to access:
Another possibility is to use a .json file:
then you access it:
Finally, outside of the stdlib is to use a YAML file with PyYAML , which for example allows you to nest sections, as you seem to initially intend, and is a very human-readable format:
then we access it something like this:
Assuming you have a file called config.ini with the following data:
You can call each of its values by its key like so:
Or iterate like this as you are doing
But with one caveat: Items must come with double quotes not single quotes.
"Chile":"190.82.76.58:32570",
If I'm not mistaken, the get function of a dictionary works like this... (Value to retrieve, and default value if it doesn't exist) That is, you would have to put config.get('proxy') When you put get(const, 'proxy') you are looking for an object equal to const, and not being found you get the value of the second parameter, that's why it tells you that the str has no items