Can I reference a dict value on dict creation?

Question:

I have this dictionary and I want to set the value of netdev["ipv6"]["addr"] with the former declared netdev["ipv6"]["prefix"].

Is there any elegant way to do this “on-the-fly” or do I have to do this outside of the dict declaration with the known mechanisms like dict.update(), … ?

net_dev = {
    "link_name": "eth0",
    "ipv4": {
        "address": "10.80.0.1",
        "mask": "255.255.255.0",
    },
    "ipv6": {
        "prefix": "2001:db8:0:1::",
        "addr": <HERE_THE_PREFIX_IS_USED> + "1234:1",
        "mask": "64",
        "prefix_range": "2001:db8:0:100::",
    }
}
Asked By: Kev Inski

||

Answers:

Yes and No! You can use f-strings (available in Python-3.6+) to automatically format strings based on already available variables which in this case can be netdev["ipv6"]["prefix"]. If You’re not aware of the value of netdev["ipv6"]["prefix"] before creating the dictionary there will be no way to do this on the fly, (at least in Cpyhon implementation or in general at Python-level). However, there might be some hacks to create a custom dictionary which re-formats the value of the intended keys as is mentioned here: Can you set a dictionary value dependant on another dictionary entry?.

PREFIX = previously_defined_prefix
net_dev = {
    "link_name": "eth0",
    "ipv4": {
        "address": "10.80.0.1",
        "mask": "255.255.255.0",
    },
    "ipv6": {
        "prefix": PREFIX,
        "addr": f"{PREFIX}1234:1",
        "mask": "64",
        "prefix_range": "2001:db8:0:100::",
    }
}

In this case PREFIX is a variable defined in the same name space as the net_dev dictionary.

In you’re using 3.6- versions instead of f-string approach you can simple use str.format() or just + operator:

PREFIX = previously_defined_prefix
net_dev = {
    "link_name": "eth0",
    "ipv4": {
        "address": "10.80.0.1",
        "mask": "255.255.255.0",
    },
    "ipv6": {
        "prefix": PREFIX,
        "addr": "{}1234:1".format(PREFIX),  # PREFIX + "1234:1"
        "mask": "64",
        "prefix_range": "2001:db8:0:100::",
    }
}
Answered By: Mazdak
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.