parse a dot seperated string into dictionary variable

python split string into dictionary
python nested dictionary dot notation
dotmap python
dot notation access to dictionary attributes
python dictionary accessors
python create object with dot notation
how to access dict with dot in python
access dict using dot notation

I have string values as,

"a"
"a.b"
"b.c.d"

How to convert them into python dictionary variables as,

a
a["b"]
b["c"]["d"]

The first part of the string (before dot) will become the dictionary name and the rest of the substrings will become the dictionary keys

eval is fairly dangerous here, since this is untrusted input. You could use regex to grab the dict name and key names and look them up using vars and dict.get.

import re

a = {'b': {'c': True}}

in_ = 'a.b.c'
match = re.match(
    r"""(?P<dict>      # begin named group 'dict'
          [^.]+        #   one or more non-period characters
        )              # end named group 'dict'
        \.             # a literal dot
        (?P<keys>      # begin named group 'keys'
          .*           #   the rest of the string!
        )              # end named group 'keys'""",
    in_,
    flags=re.X)

d = vars()[match.group('dict')]
for key in match.group('keys'):
    d = d.get(key, None)
    if d is None:
        # handle the case where the dict doesn't have that (sub)key!
        print("Uh oh!")
        break
result = d

# result == True

Or even more simply: split on dots.

in_ = 'a.b.c'
input_split = in_.split('.')
d_name, keys = input_split[0], input_split[1:]

d = vars()[d_name]
for key in keys:
    d = d.get(key, None)
    if d is None:
        # same as above
result = d

Python - How to split string into a dict, 1.1 Split a string into a dict. #!/usr/bin/python str = "key1=value1;key2=value2; key3=value3� Question: Tag: python,string,dictionary I have string values as, "a" "a.b" "b.c.d" How to convert them into python dictionary variables as, a a["b"] b["c"]["d"] The first part of the string (before dot) will become the dictionary name and the rest of the substrings will become the dictionary keys

s = "a.b.c"
s = s.replace(".", "][")+"]" # 'a][b][c]'
i = s.find("]") # find the first "]"
s = s[:i]+s[i+1:] # remove it 'a[b][c]'
s = s.replace("]", "\"]").replace("[", "[\"") # add quotations 'a["b"]["c"]'
# you can now execute it:
v = eval(s)

Python, Python - Convert Dictionary to Concatenated String � Python | Convert dictionary object into string � Python | Convert nested dictionary into� How to parse strings using String.Split in C#. 01/03/2018; 2 minutes to read +3; In this article. The String.Split method creates an array of substrings by splitting the input string based on one or more delimiters. This method is often the easiest way to separate a string on word boundaries.

I ran into this same problem for parsing ini files with dot-delimited keys in different sections. e.g.:

[app]
site1.ftp.host = hostname
site1.ftp.username = username
site1.database.hostname = db_host
; etc..

So I wrote a little function to add "add_branch" to an existing dict tree:

def add_branch(tree, vector, value):
    """
    Given a dict, a vector, and a value, insert the value into the dict
    at the tree leaf specified by the vector.  Recursive!

    Params:
        data (dict): The data structure to insert the vector into.
        vector (list): A list of values representing the path to the leaf node.
        value (object): The object to be inserted at the leaf

    Example 1:
    tree = {'a': 'apple'}
    vector = ['b', 'c', 'd']
    value = 'dog'

    tree = add_branch(tree, vector, value)

    Returns:
        tree = { 'a': 'apple', 'b': { 'c': {'d': 'dog'}}}

    Example 2:
    vector2 = ['b', 'c', 'e']
    value2 = 'egg'

    tree = add_branch(tree, vector2, value2)    

    Returns:
        tree = { 'a': 'apple', 'b': { 'c': {'d': 'dog', 'e': 'egg'}}}

    Returns:
        dict: The dict with the value placed at the path specified.

    Algorithm:
        If we're at the leaf, add it as key/value to the tree
        Else: If the subtree doesn't exist, create it.
              Recurse with the subtree and the left shifted vector.
        Return the tree.

    """
    key = vector[0]
    tree[key] = value \
        if len(vector) == 1 \
        else add_branch(tree[key] if key in tree else {},
                        vector[1:],
                        value)
    return tree

scalpl � PyPI, Scalpl provides a lightweight wrapper that helps you to operate on nested dictionaries seamlessly through the built-in dict API, by using dot-separated string � >>> help(ast.literal_eval) Help on function literal_eval in module ast: literal_eval(node_or_string) Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

The pyjq library does something quite similar to this, except you have to explicitly provide a dictionary to be the root, and you have to prefix your strings with a . to refer to whatever dictionary was your root.

python:

import pyjq
d = { 'a' : { 'b' : { 'c' : 'd' } } }
for path in ['.a', '.a.b', '.b.c.d', '.x']:
    print(pyjq.first(path, d))

output:

{'b': {'c': 'd'}}
{'c': 'd'}
None
None

dotty-dict � PyPI, Simple wrapper around python dictionary and dict like objects; Two wrappers with the same dict are considered equal; Access to deeply nested keys with dot� I have a character variable of varying lengths that I want to separate into separate variables. The variable always follows the following pattern - AA.AA.AA.AA.AA (2 characters then a period, 2 characters then a period, etc) - and each "AA" signifies a unique code I need to have separated for further analysis. Example of what it looks like now:

Python Split String Examples, Split. Strings often store many pieces of data. In a comma-separated format, these Here we handle a string that contains city names separated by commas. t) # Set string variable to non-partitioned part. s = t[2] Output Dot ('Dot', ' ', 'Net Perls� These are good differences to point out; another important one is that -split takes a regex (regular expression) as its (first) RHS operand, whereas the [string] type's .Split() method operates on a literal character / array of characters / and - in .NET Core - also a literal string.

6. Dictionaries, sets, files, and modules — Beginning Python , As an example, we will create a dictionary to translate English words into Spanish. Each pair contains a key and a value separated by a colon. Whenever two variables refer to the same object, changes to one affect the other. The easiest and most powerful way to format a string in Python 3 is to use the format method. The split method breaks the string into an array where the character we pass in to the method (in this case, a comma) separates each element in the array. So, the first element of the array is comma one, the second is comma two and the fourth is comma four. Remember that arrays begin at the 0th character, not the first.

DICTIONARY, where Key is an IDL variable containing a scalar string. Or you can use dot notation: value =� parse a dot seperated string into dictionary variable. python,string,dictionary. eval is fairly dangerous here, since this is untrusted input. You could use regex to grab the dict name and key names and look them up using vars and dict.get. import re a = {'b': {'c': True}} in_ = 'a.b.c' match = re.match( r"""(?P<dict> # begin named group 'dict

Comments
  • How is the output a dictionary?
  • Didn't get the question. What do you actually want to happen? Can you be more specific? Do you want a to be a dictionary with key b, and then b to be a dictionary with key c which has a dictionary as value, which has key d?
  • yes tomasyany... the first part of the string (before dot) will become the dictionary name and the rest of the substrings will become the dictionary keys...
  • So a will be the variable that stores the dictionary of dictionaries?
  • this evaluates to a[b][c] as against a["b"]["c"]. To solve this, i added two more lines before eval as, s = s.replace("]", "\"]") and s = s.replace("[", "[\"").
  • Oh, I should fix it then
  • Super helpful. I'm using this as a crossover for people to use and excel sheet with columns labeled in this pattern so that I can do bulk api calls though I needed to add a bit to the logic to get it to work: rowObj.update(add_branch(rowObj,colName.split("."),rowValue))