D
D
denislysenko2021-11-25 11:40:43
Python
denislysenko, 2021-11-25 11:40:43

How can sys.stdin which looks like a dictionary be turned into a dictionary?

sys.stdin looks like this:
{'Action': ['Terminal Velocity;1994', 'Terminator 2: Judgment Day;1991', 'Terminator, The;1984', 'Terminator 3: Rise of the Machines;2003', ' Terminator Salvation;2009', 'Terminator Genisys;2015'], 'Mystery': ['Terminal Velocity;1994'], 'Thriller': ['Terminal Velocity;1994', 'Terminator, The;1984', 'Terminator Salvation ;2009', 'Terminator Genisys;2015'], 'Sci-Fi': ['Terminator 2: Judgment Day;1991', 'Terminator, The;1984', 'Terminator 3: Rise of the Machines;2003', ' Terminator Salvation;2009', 'Terminator Genisys;2015'], 'Adventure': ['Terminator 3: Rise of the Machines;2003', 'Terminator Salvation;2009', 'Terminator Genisys;2015'], 'Comedy': ['Terminal, The;2004'], 'Drama': ['Terminal, The;2004'], 'Romance': ['Terminal, The;2004']}

me need to continue to use this dictionary
How can I turn it into a dict variable?
here is my code

# sort.py 

import sys
import json

def dict_sorted_by_genre(dict_data):
    # sort genres by alphabetically
    sorted_result = sorted(dict_data.items(), key=lambda x: x[0])
    dict_result = dict(sorted_result)
    return dict_result


if __name__ == "__main__":
    dict = json.loads(str(sys.stdin))
    sorted_dict = dict_sorted_by_genre(dict)
    print(sorted_dict)


this is the command run:
[email protected] homework5 % cat files/movies.csv | python3 mapper.py -regexp Termi | python3 shuffle.py | python3 sort.py throws

this error:
Traceback (most recent call last):
File "/Users/denislysenko/Desktop/Intern/coherent-training-denis-lysenko/homework5/sort.py", line 12, in
dict = json .loads(str(sys.stdin))
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/json/__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0 ).end())
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json .decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Exception ignored in: <_io.TextIOWrapper name='' mode='w' encoding='utf-8'>
BrokenPipeError: [Errno 32] Broken pipe

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2021-11-25
@denislysenko

Have you tried printing str(sys.stdin) to the screen?

>>> str(sys.stdin)
"<_io.TextIOWrapper name='<stdin>' mode='r' encoding='utf-8'>"

sys.stdin is a file opened in text mode. Work with it like a file.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question