0

Let's say I have the dictionary my_dict:

my_dict = {"vms": {"vm": {"name": "test-vm", "desc": "test"}}} 

Obviously, in code I can grab the VM data with:

my_dict['vms']['vm']

More to the point, I can create an object of vms with that value and then reference the data:

vms = my_dict['vms']
vm = vms['vm']

My question is, if I were to save the value vms['vm'] as a string in a configuration file, how can I then use said string to grab the value from the dictionary? Something like:

my_dict.grab("vms['vm']")    # To grab my_dict['vms']['vm']

I'm hoping a solution that I can further use with, say, vms['vm']['name'] regardless of how nested it gets, akin to Ansible Facts in a YAML playbook:

my_dict.grab("vms['vm']['name']")
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • That would be unnecessarily difficult. Why not store something like "vms.vm" or "vms.vm.name" instead? – mkrieger1 Aug 27 '21 at 18:45
  • It's fairly easy if you agree to use dot notation strings instead: https://stackoverflow.com/a/32404277/1453822 – DeepSpace Aug 27 '21 at 18:46
  • Important to understand, when you say " I can create an object of vms with that value " that *isnt' what you are doing*. You aren't creating an object at all when you do: `vms = my_dict['vms']`... you are *assigning an existing object to the name `vms`* – juanpa.arrivillaga Aug 27 '21 at 19:04
  • 1
    In any case, storing that string as a value in a configuration file doesn't make sense. **Strings are not source code** I mean, you can use `exec`/`eval` to dynamically evaluate a string as source code, but that is extremely hackey. Just pick a format which is easy to parse and work with programmatically – juanpa.arrivillaga Aug 27 '21 at 19:05
  • @juanpa.arrivillaga I understand the oddity of the request generally, but I'm trying to build a system with a similar workflow to an Ansible Playbook a la {{ ansible_facts["eth0"]["ipv4"]["address"] }} – John Mansell Aug 27 '21 at 19:53
  • Yeah, so they are probably just using `eval` – juanpa.arrivillaga Aug 27 '21 at 20:04
  • @juanpa.arrivillaga I just got it working, I'm going to guess they use Jinja2 directly – John Mansell Aug 27 '21 at 20:16

1 Answers1

0

So it turns out what I was looking for was Jinja2

from jinja2 import Template

my_dict = {"vms": {"vm": {"name": "test-vm", "desc": "test"}}}
string_location = "{{ vms['vm'] }}"

print(Template(string_location).render(my_dict))