0

Im calling an API that gives the output in an array. This is the array data.

["{'meta':'projects/us/conf/94eb2c1f0574'}","{'del':'projects/us/conf/001a1143e726'}"]

Here I want to extract the value for the key meta.

Expected output:

projects/us/conf/94eb2c1f0574

How can I do this with Python? Also, the output is in correct array structure?

2
  • Are you asking how to use dicts and lists? Commented Jul 30, 2020 at 23:36
  • Im new to Python concepts, not sure its dicts or list. Basically something like print(array(meta)) Please check the expected output. Commented Jul 30, 2020 at 23:38

4 Answers 4

1

If you mean get the value where the key is meta you can use next and a comprehension:

data = ["{'meta':'projects/us/conf/94eb2c1f0574'}","{'del':'projects/us/conf/001a1143e726'}"]

>>> next(v for (k, v) in map(dict.items, data) if k == 'meta')
projects/us/conf/94eb2c1f0574
Sign up to request clarification or add additional context in comments.

Comments

0

Quick fix would be to convert data[0] to a dict using json.loads -

value = json.loads(d[0].replace('\'','"'))['meta']

Comments

0

Assuming this is array is loaded into the variable data, data[0] is the dictionary with one key 'meta'. From there, you can access that key by passing the name.

>>> data = [{'meta':'projects/us/conf/94eb2c1f0574'}, {'del':'projects/us/conf/001a1143e726'}]
>>> data[0]['meta']
'projects/us/conf/94eb2c1f0574'

1 Comment

thats a big assumption based on OP ... i would take him at his word about the weird return ... seems like a bug with the api though
0

if your input is really looking like that (bad api design, or a bug in the API)

you can just load each as json

fixed = [json.loads(string_thing.replace("'",'"')) for string_thing in response_array]

 >>> fixed[0]['meta']
 u'projects/us/conf/94eb2c1f0574'
 >>> fixed[1]['del']
 u'projects/us/conf/001a1143e726'

if you wanted to make it one big dict

data = {}
for string_thing in response_array:
    # this assumes the strings are valid json and always dicts
    data.update(json.loads(string_thing.replace("'",'"')))

>>> data
{u'meta': u'projects/us/conf/94eb2c1f0574', u'del': u'projects/us/conf/001a1143e726'}
>>> data['meta']
u'projects/us/conf/94eb2c1f0574'
>>> data['del']
u'projects/us/conf/001a1143e726'

Comments

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.