0

I'm wondering if this is possible in python. I'm accessing a list in this way:

print list[0]['name']

This is fine. Is there a way to use a variable? I mean:

a="[0]['name']"
print list[a]

Thanks for your suggestions.

Some details:

I have a situation where I have something like this:

a = [{"name":"someone", "age":23}]
print a[0]['name']

But since I need to pass "[0]['name']" as parameter, I'd like to understand if this is possible. Thanks,

cips

cips
  • 39
  • 1
  • 1
  • 7

5 Answers5

2

This is a simple matter of extracting the indices/keys from the string "[0]['name']" and then using those keys to index the list/dict structure.

data = [{"name":"someone", "age":23}]
keys = "[0]['name']"

# split the string into a list of indices/keys
keys = keys[1:-1].split('][')
# keys = ['0', "'name'"]

# the keys are all strings, so we have to convert
# each individual key to the correct type
import ast
keys = [ast.literal_eval(key) for key in keys]
# keys = [0, 'name']

# now use the list of indices/keys we generated to get the value
value = data
for key in keys:
    value = value[key]

print(value) # output: someone
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
0

I hope not to be out of context, but maybe you can use a function like this if you can convert s = "[0]['name']" to s = (0, 'name'):

def search_index(obj, itero):
    try:
        return search_index(obj[next(itero)], itero)
    except StopIteration:
        return obj

a = [{"name":"someone", "age":23}]
s = (0, 'name')

result = search_index(a, iter(s))
# >>> result = 'someone'

If you want to convert "[0]['name']" to (0, 'name') you can try this:

import re
reg = re.findall(r'\[(\d*?)\]|\[\'(\w*?)\'\]', "[0]['name']")
s = [int(index[0]) if not index[1] else index[1] for index in reg]
# [0, 'name']

It will convert the indexes to the right type, to work with either list or dicts.

Guillaume Lebreton
  • 2,586
  • 16
  • 25
-3

In general it is dangerous to use eval but you essentially need to convert your string to perform your indexing.

So first you can get your list as a str using repr

>>> l = [{'name': 'bob'}]
>>> repr(l)
"[{'name': 'bob'}]"

then if you concatenate that with your index operation

>>> a = "[0]['name']"
>>> repr(l) + a
"[{'name': 'bob'}][0]['name']"

then eval the whole thing, it should do the trick

>>> eval(repr(l) + a)
'bob'
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • 1
    Please, no. Avoiding `eval` is almost _trivial_ in this case; you can easily parse the string `"[0]['name']"` into a list like `[0, 'name']` and then use those values to index `a`. – Aran-Fey Sep 15 '17 at 08:10
-3

you can use the function eval('a[0][name]'), it will evaluate the string inside as a python code.

here is the reference: https://docs.python.org/3/library/functions.html#eval

  • Welcome to StackOverflow. Please read [answer] to write better answers in the future. – Marco Sep 14 '17 at 23:20
  • 1
    Please don't advocate the use of `eval` or `exec`. It's near-trivial to solve the OP's problem _without_ `eval`. `eval` opens a massive security hole in your code for no reason. – Aran-Fey Sep 15 '17 at 08:06
-4

You can use exec command

exec("print(list{})".format(a))

I hope it works

  • 2
    Please don't advocate the use of `eval` or `exec`. It's near-trivial to solve the OP's problem _without_ `exec`. `exec` opens a massive security hole in your code for no reason. – Aran-Fey Sep 15 '17 at 08:07