Sina Sh Sina Sh - 1 year ago 91
Python Question

Append multiple values for a key from a file

I've got a file similar to below:


I want to make a dictionary in order to assign those values of laten and periodic to each key of t_air_sens1 and etc. The final result must be something like below:

"t_air_sens1": [laten,periodic]
"t_air_air": [laten,periodic]

I did write the code below:

prop_dict = {}
with open('') as f, open('', 'w') as procode:
for line in f:
if line[0] in prop_dict:
prop_dict[line[0]] = [line[1]]
#will write the values in ""

But the result I get when I try to print the dictionary is something like below:

{'p': ['e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e'],
't': ['_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_',
'_', '_', '_', '_', '_', '_', '_', '_', '_'],
'l': ['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a']}

What can I do to fix it? How do I need to make queries in order to get the proper result?

Answer Source

line[0] and line[1] are single characters in the string, not the current line and the next.

File objects are iterators; the for loop will get new lines from it each iteration, but you can also use the next() function to pull another line in. Use this to read two lines at a time:

prop_dict = {} 
with open('') as f:
     for key in f:
         key = key.rstrip('\n')
         # get the next line as the value
         value = next(f).rstrip('\n')
         prop_dict.setdefault(key, []).append(value)

I also used dict.setdefault() to insert an empty list for any key that is missing from the dictionary. Like prop_dict[key], it'll return the current value in the dictionary, but if there is no such key, prop_dict[key] = [] is executed first before returning that empty list.

How the above works is that the for loop reads lines one by one as the loop iterates, basically by using next() internally. Calling next(f) in the loop simply draws in an extra line, and the for loop continues from there again, so you are alternating between reading a property name (key), and a property value (value).

Note that next() can raise a StopIteration exception if the end of the file was reached by reading the last line in the for loop; this would indicate your file did not have an even number of lines. If this is not an error, you could specify a default instead: next(f, '') would return the empty string '' if the file has been exhausted.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download