Makiyo
Makiyo

Reputation: 451

Python: String to list (without changing a word)

** If you try to run code, please set Tall as string, thanks.

I scraped this from the website from POST, Tall looks like a list but it is not. It is a "string", I already used some split to make it neat. I just want to know if there a way to make it as a list and use simple way to extract data. Otherwise it'll be difficult for me to split all of them.

Type of Tall is string and I want to extract values from Tall:

Tall=[{"SALEDATE":"2018/02/06","CARID":"2002","CERTPHOTO1":"Y"},
 {"SALEDATE":"2018/02/06","CARID":"4791","CERTPHOTO1":""}]

Code:

print(type(Tall))

class 'str'

print(Tall[1])

{

But when I tried to do this:

for i in range(2):
    result=list(Tall[i].values())

The error says:

AttributeError: 'str' object has no attribute 'values'

I want to make Tall from string to a list without changing anything of Tall, is it possible?

The result I expected:

2018/02/06,2002,Y
2018/02/06,4791,

Upvotes: 0

Views: 173

Answers (3)

Steffi Keran Rani J
Steffi Keran Rani J

Reputation: 4103

Using __getitem__ special method is one simplest way to achieve your desired result.

Here's how I have solved your problem:

Tall=[{"SALEDATE":"2018/02/06","CARID":"2002","CERTPHOTO1":"Y"}, {"SALEDATE":"2018/02/06","CARID":"4791","CERTPHOTO1":""}]
for i in Tall:
    sale = i.__getitem__('SALEDATE')
    carid = i.__getitem__('CARID')
    photo = i.__getitem__('CERTPHOTO1')
    print(sale,',',carid,',',photo)

On executing the above code, we'll land up in the exact result you had asked for:

2018/02/06, 2002, Y
2018/02/06, 4791,

Upvotes: 0

northtree
northtree

Reputation: 9265

I suppose your TALL is str like this. (Added single quotes to be string). The answer to your question (how to convert string to list) is via eval.

>>> tall_str = '[{"SALEDATE":"2018/02/06","CARID":"2002","CERTPHOTO1":"Y"},{"SALEDATE":"2018/02/06","CARID":"4791","CERTPHOTO1":""}]'
>>> print(type(tall_str))
<class 'str'>

(1) json.loads

>>> import json
>>> tall_list = json.loads(tall_str)
>>> print(type(tall_list))
<class 'list'>

(2) eval

>>> tall_list = eval(tall_str)
>>> print(type(tall_list))
<class 'list'>

Upvotes: 3

bla
bla

Reputation: 1870

You may use json.loads() for that:

>>> import json
>>> tall = json.loads('[{"SALEDATE":"2018/02/06", "CARID":"2002","CERTPHOTO1":"Y"},{"SALEDATE":"2018/02/06","CARID":"4791","CERTPHOTO1":""}]')
>>> tall
[{'SALEDATE': '2018/02/06', 'CARID': '2002', 'CERTPHOTO1': 'Y'}, {'SALEDATE': '2018/02/06', 'CARID': '4791', 'CERTPHOTO1': ''}]
>>> tall[0]
{'SALEDATE': '2018/02/06', 'CARID': '2002', 'CERTPHOTO1': 'Y'}
>>> tall[0].values()
dict_values(['2018/02/06', '2002', 'Y'])

Upvotes: 1

Related Questions