Reputation: 147
I have a txt file with key value pairs. It can format (get, retrieve) the pairs from the file in multiple ways, for example:
as line separated strings with colons:
stringa1:stringa2
stringb1:stringb2
or as line separated strings with commas:
stringa1,stringa2
stringb1,stringb2
or as individuals lists of strings:
[stringa1,stringa2]
['stringa1','stringa2']
AND, I can assign each string to a variable with:
for string in list
splitstring=list.split(',')
for item in splitstring:
print (item)
>>>stringa1
>>>stringa2
But I can't figure out how to add those key:value pairs to a dictionary
Upvotes: 1
Views: 161
Reputation: 6466
d[splitstring[0]] = splitstring[1]
should work, where d is a dict. That's the easiest way of adding a key, value pair to a dictionary.
Another way is:
d.update({splitstring[0]: splitstring[1]})
Upvotes: 1
Reputation: 996
Taking in mind that we are talking about pairs, then this should work:
mydict = {}
for i in range(0,len(splitstring),2):
mydict[splitstring[i]] = splitstring[i+1]
Upvotes: 1