Python Forum
Getting a certain value from inside brackets.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Getting a certain value from inside brackets.
#1
Hi there,
I'm a beginner so this problem might be very ease to solve.
Im doing a request to a device that responds with the following raw data:
[{u'address': {u'altitude': None,
               u'area': u'',
               u'buildingNumber': None,
               u'country': None,
               u'latitude': None,
               u'longitude': None,
               u'street': u'',
               u'zip': u''},
  u'id': 63XXXX,
  u'levelOfAccess': None,
  u'name': u'Schuppen',
  u'siteKey': u'YBCL-HXXX'}]
I basically want to save the value of 'siteKey', meaning YBCL-HXXX into a variable.
I had the problem before and could solve it using this method:
variableX = exampledata['siteKey']
With this method I get the following error:
TypeError: list indices must be integers, not str

I think it has to do with a different format of the raw data, because all my other raw data that I can put into a variable using the explained method is not [....] but only in {....}
I hope some of you can help me...
Best,
Leo
Reply
#2
First: Use Python 3.x. You're still using Python 2.

data = [{'address': {'altitude': None,
              'area': '',
              'buildingNumber': None,
              'country': None,
              'latitude': None,
              'longitude': None,
              'street': '',
              'zip': ''},
  'id': 63,
  'levelOfAccess': None,
  'name': 'Schuppen',
  'siteKey': 'YBCL-HXXX'}]
The type of data is a list. A list has the subscription method to access with an index an element in the list. Inside your list is a dict.

Changing the siteKey of the first dict in the list:
data[0]["siteKey"] = "ABC"

# or

data[0].update({"siteKey": "ABC"})
*) Indexing begins with 0

If you have many elements in your list and want to update all existing siteKey, you can iterate over your list and update the dicts.

# if data is your list:
for entry in data:
    entry["siteKey"] = "ABC"
If you have more than one key to update, then the update method of the dict is the better approach.

my_creds = {"user": "foo", "password": "123", "token": "xyz", "siteKey": "ABC"}

for entry in data:
    entry.update(my_creds)
If there is the case, where data (the list) is empty, the for-loop will do nothing and the subscription to index 0 of the list, will raise an IndexError exception.

So if you always expect one entry in the list, check the list of Truth.

empty_list = []
non_empty_list = [{}] # one dict inside, not empty

# not is a boolean negation
if not empty_list:
    print("empty_list is empty")

# empty_list will evaluate to False

if non_empty_list:
    print("non_empty_list is not empty")
    # then you can access index 0

# non_empty_list will evaluate to True, because it's not empty
nilamo likes this post
My code examples are always for Python >=3.6.0
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#3
Hi there,
I'm a beginner so this problem might be very ease to solve. Nevertheless I posted this question a few days ago and got no helping answer. I hope that someone of you has an idea.

I'm doing a GET request:
requests.get('https://api.xyz.cloud/api/sites/%s?detailed=true' % xyz_site_id, timeout=None, headers=self.headers).json()
to a device that responds with the following raw data:
[{u'address': {u'altitude': None,
               u'area': u'',
               u'buildingNumber': None,
               u'country': None,
               u'latitude': None,
               u'longitude': None,
               u'street': u'',
               u'zip': u''},
  u'id': 63XXXX,
  u'levelOfAccess': None,
  u'name': u'Schuppen',
  u'siteKey': u'YBCL-HXXX'}]
I basically want to save the value of 'siteKey', meaning YBCL-HXXX into a variable to use this variable for further actions...

I had this problem before and could solve it using this method:
variableX = exampledata['siteKey']
Nevertheless, when using this method now I get the following error:
TypeError: list indices must be integers, not str

Btw. I have to use Python 2.7 due to various reasons...

I think it has to do with a different format of the raw data (a 'list').
I'm searching for a solution for hours now and hope that some of you can help me...
Best,
Leo
Reply
#4
Please, don't start new threads unnecessarily. Why do you say you got no helping answer?
@DeaD_EyE answer is waht you want. What is that you don't like about it.

You have list of dicts. You access elements in the list by index.

data = [{u'address': {u'altitude': None,
               u'area': u'',
               u'buildingNumber': None,
               u'country': None,
               u'latitude': None,
               u'longitude': None,
               u'street': u'',
               u'zip': u''},
  u'id': 123456,
  u'levelOfAccess': None,
  u'name': u'Schuppen',
  u'siteKey': u'YBCL-HXXX'}]

spam = data[0][u'siteKey'] # access element at index 0 and get value for key
print(spam)
if you have more than one item in the list, you may have to iterate over items in the list.

for item in data:
    spam = item[u'siteKey']
    print(spam)
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
I'm sorry. It seems like I did not understand his answer probably.

I thought he misunderstood me and due to this answered wrongly.
Thanks for making it clear again.
It works fine now!
Reply
#6
(Mar-01-2021, 03:08 PM)LeoT Wrote: I'm sorry. It seems like I did not understand his answer probably.
On a second reading, there myght have been some misunderstanding, also on my part. Indeed he talks about changing value.. Not exactly what you asked for
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Removing internal brackets from a string Astrikor 4 817 Jun-04-2020, 07:54 PM
Last Post: Astrikor
  Taking brackets out of list in print statement pythonprogrammer 3 1,029 Apr-13-2020, 12:25 PM
Last Post: perfringo
  printing a list contents without brackets in a print statement paracelx 1 823 Feb-15-2020, 02:15 AM
Last Post: Larz60+
  Dictionnary brackets issue Reldaing 1 729 Nov-10-2019, 11:54 PM
Last Post: ichabod801
  how to remove brackets within a list A3G 17 11,742 Oct-16-2016, 02:34 PM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020