1

I am new to Python and I wanted to input a dictionary through command line and have below code print the key:

for line in sys.stdin:

    adict ={}
    line = line.strip()
    adict = line

    for key, value in adict.items():
        print(key)

I keep getting the error: AttributeError: 'str' object has no attribute 'items'.

When I try to create a dictionary and print it, it does:

data = {}
data[str(0) + str(1)] = "A " +  str(0) + " " + str(1.0) 

for key, value in data.items():
    print(key)

Why am I not able to enter a dictionary from the command line and have the key printed? I am taking the dictionary input ({'01': 'A 0 1.0'}) and storing it in a dictionary variable, adict. adict prints correctly but why can't I use items() on it? Am I doing something incorrectly?

1
  • 1
    you just overwrote your dict by the line which is a string!!! what do you expect? what should be the key to your data? Commented Feb 4, 2017 at 20:34

2 Answers 2

2

line is a string and you've only rebound the adict name to the stripped string, so you don't have a dict, but a string.

You can instead use ast.literal_eval to build your dictionary from the inputted string:

import ast

adict = ast.literal_eval(input())
Sign up to request clarification or add additional context in comments.

Comments

0

check your adict types to see how it changes through the code:

for line in sys.stdin:

    adict ={}
    line = line.strip() # line here is a string
    adict = line   # so adict will be a string

    for key, value in adict.items():  # string doesn't have item attribute
        print(key)

2 Comments

Thanks. I understood a lot from this. But my issue persists. for line in sys.stdin is always a string, if i am correct. but my input is dictionary. How do I extract my key, value from a string? split seems a lot of work and could be incorrect for large input. what should i do?
see moses answer , he suggest you a way

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.