0

I'm trying to assign two values of a list to two different variables. Here is the json list. Its raising key error. Please let me know where I am wrong.

[{'min': 1.158, 'max': 1.150, 'id': 269097, 'to': 1532003820, 'from': 1532003760, 'check': 1.15852, 'no_check': 1.15822, 'volume': 0},{'min': 1.1, 'max': 1.17, 'id': 269098, 'to': 1532003880, 'from': 1532003820, 'check': 1.158615, 'nocheck': 1.158515, 'volume': 0}]

Here is my code python3 code:

pt = [{'min': 1.158, 'max': 1.150, 'id': 269097, 'to': 1532003820, 'from': 1532003760, 'check': 1.15852, 'no_check': 1.15822, 'volume': 0},{'min': 1.1, 'max': 1.17, 'id': 269098, 'to': 1532003880, 'from': 1532003820, 'check': 1.158615, 'nocheck': 1.158515, 'volume': 0}]

y = [item[0] for item in pt]
z = [item[0] for item in pt]
print(y)
print(z)

Error:

File "test_YourM.py", line 19, in <module>
  y = [item[0][0] for item in pt]   File "test_YourM.py", line 19, in <listcomp>
  y = [item[0][0] for item in pt] KeyError: 0

Expected output:

print(y) # {'min': 1.158, 'max': 1.150, 'id': 269097, 'to': 1532003820, 'from': 1532003760, 'check': 1.15852, 'no_check': 1.15822, 'volume': 0}
print(z) # {'min': 1.1, 'max': 1.17, 'id': 269098, 'to': 1532003880, 'from': 1532003820, 'check': 1.158615, 'nocheck': 1.158515, 'volume': 0}
martineau
  • 119,623
  • 25
  • 170
  • 301
Saikumar A
  • 35
  • 3
  • 2
    You have a list of dictionaries. You need to access it using a `key` – Rakesh Jul 19 '18 at 12:56
  • 2
    `item[0]` doesn't exist, you could try `item['min']` etc. – Nick is tired Jul 19 '18 at 12:56
  • 1) The code in the error message is different from the code in your question; please decide which code you want to use and what error it produces; 2) what _is_ `item[0]`? What do you expect it to be? – ForceBru Jul 19 '18 at 12:59
  • 1
    Following your edit, what's wrong with `y, z = pt`? – Nick is tired Jul 19 '18 at 13:00
  • Possible duplicate of [Python: Assign each element of a List to a separate Variable](https://stackoverflow.com/questions/19300174/python-assign-each-element-of-a-list-to-a-separate-variable) – Nick is tired Jul 19 '18 at 13:02

1 Answers1

0
[item for item in pt[0]]
[item for item in pt[1]]

The item is generated in in that scope, while pt isn't, even though you're enumerating a dict, you may want to do something like this:

{key: value for key, value  in pt[0].items()}
{key: value for key, value  in pt[1].items()}
Hagai Wild
  • 1,904
  • 11
  • 19