Skip to content Skip to sidebar Skip to footer

How To Assign A Value To A String?

I am given a list containing tuples for example: a=[('bp', 46), ('sugar', 98), ('fruc', 56), ('mom',65)] and a nested list, in a tree structure tree= [ [ 'a',

Solution 1:

I would suggest a recursive traversion of the tree:

a=[('bp', 46), ('sugar', 98), ('fruc', 56), ('mom',65)]
d = dict(a)
tree= [
    [
        'a',
        'bp',
        [78, 25, 453, 85, 96]
    ],
    [
        ['hi', ['no', ['ho', 'sugar', 3]], ['not', 'he', 20]],
        [['$', 'fruc', 7185], 'might', 'old'],
        'bye'
    ],
    [
        ['not', ['<', 'mom', 385]],
        [
            ['in', 'Age', 78.5],
            [['not', ['and', 'bp', 206]], 'life', [['or', ['not', ['\\', 'bp', 5]], ['p', 'sugar', 10]], 'ordag',[['perhaps', ['deal', 'mom', 79]],
            'helloo',[['or', ['pl', 'mom', 25]], 'come', 'go']]]],
            'noway'
        ],
        [['<', 'bp', 45], 'falseans', 'bye']
    ]
]



defreplace(node):
    ifisinstance(node, str):
        return d.get(node, node)
    elifisinstance(node, list):
        return [replace(el) for el in node]
    else:
        return node

replace(tree)

Solution 2:

Quick hack, works in simple cases.

(note: you have an incorrect string here: '\' should be '\\')

  • convert the structure to string
  • perform the replacement using single quotes as a delimiter so it's safe against word inclusions in other bigger words
  • parse back the string with replacements using ast.literal_eval which does the heavy lifting (parsing back the valid literal structure text to a valid python structure)

code:

tree= [['a', 'bp', [78, 25, 453, 85, 96]],
[['hi', ['no', ['ho', 'sugar', 3]], ['not', 'he', 20]],
[['$', 'fruc', 7185], 'might', 'old'],
'bye'],[['not', ['<', 'mom', 385]],
[['in', 'Age', 78.5],[['not', ['and', 'bp', 206]],
'life',[['or', ['not', ['\\', 'bp', 5]], ['p', 'sugar', 10]],
'ordag',[['perhaps', ['deal', 'mom', 79]],
'helloo',[['or', ['pl', 'mom', 25]], 'come', 'go']]]],
'noway'],[['<', 'bp', 45], 'falseans', 'bye']]]
a=[('bp', 46), ('sugar', 98), ('fruc', 56), ('mom',65)]

str_tree = str(tree)

for before,after in a:
    str_tree = str_tree.replace("'{}'".format(before),str(after))

new_tree = ast.literal_eval(str_tree)
print(type(new_tree),new_tree)

result:

<class'list'> [['a', 46, [78, 25, 453, 85, 96]], [['hi', ['no', ['ho', 98, 3]], ['not', 'he', 20]], [['$', 56, 7185], 'might', 'old'], 'bye'], [['not', ['<', 65, 385]], [['in', 'Age', 78.5], [['not', ['and', 46, 206]], 'life', [['or', ['not', ['\\', 46, 5]], ['p', 98, 10]], 'ordag', [['perhaps', ['deal', 65, 79]], 'helloo', [['or', ['pl', 65, 25]], 'come', 'go']]]], 'noway'], [['<', 46, 45], 'falseans', 'bye']]]

So it's a hack but it's able to process data containing sets, lists, dictionaries, tuples, without too much hassle.

Post a Comment for "How To Assign A Value To A String?"