简体   繁体   中英

Representing data-structure in python

What's the best way to represent this data-structure in python:

[{'x': 230, 'y': 50}, {'x': 350, 'y': 50}, {'x': 410, 'y': 50}]

It's not json, it's something else, sorry for my stupidity, I'm searching various python tutorials, but can't figure out if it's some structure that can be easily loaded like numpy.load or json.loads, because when I try validating that structure as JSON, it says invalid json...

What you have there is a list of dictionaries.

myList = []

dict1 = {'x': 230, 'y': 50}
dict2 = {'x': 350, 'y': 50}
dict3 = {'x': 410, 'y': 50}

myList.append(dict1)
myList.append(dict2)
myList.append(dict3)

You have a list of three dictionaries (mappings of keys to values) and it works like this:

>>> dicts = [{'x': 230, 'y': 50}, {'x': 350, 'y': 50}, {'x': 410, 'y': 50}]
>>> dicts[0]
{'x': 230, 'y': 50}
>>> dicts[0]['x']
230
>>> dicts[2]['y']
50

Since all the dictionaries share the same keys ( 'x' and 'y' ) in your example you can interpret them as records .

A neat way to represent these records is with a pandas.DataFrame , which has a table-like printout.

>>> import pandas as pd
>>> pd.DataFrame(dicts)
     x   y
0  230  50
1  350  50
2  410  50

If you have a string

>>> s = "[{'x': 230, 'y': 50}, {'x': 350, 'y': 50}, {'x': 410, 'y': 50}]"

you can evaluate it safely with ast.literal_eval .

>>> from ast import literal_eval
>>> literal_eval(s)
[{'x': 230, 'y': 50}, {'x': 350, 'y': 50}, {'x': 410, 'y': 50}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM