0

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...

12
  • Well that is a list of dictionaries, what do you want to do with that data? Commented Dec 7, 2018 at 18:34
  • 1
    It's not JSON, but it easily could be made as such. json.dumps() would suffice to serialize it. Your question is unclear to me. Commented Dec 7, 2018 at 18:35
  • load/parse it into dictionary of x/y coordinates... Commented Dec 7, 2018 at 18:37
  • 1
    But it already is that. It's a list of dictionaries. Where does JSON come into this? Commented Dec 7, 2018 at 18:38
  • 1
    my_list[1]['x'].... Commented Dec 7, 2018 at 18:40

2 Answers 2

1

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}]
Sign up to request clarification or add additional context in comments.

2 Comments

I have actually loaded above code with dicts = eval( another variable with that string)...
@AleksandarPavić consider ast.literal_eval, it's the save version of eval for literals like strings, lists, dicts, ...
1

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)

1 Comment

But I can't just something.load it? I need to do string parser for it? to break on } , { and append it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.