user2251503
user2251503

Reputation: 197

How to convert python dictionary to tcl keyed list format?

I have python file sample.py and tcl file test.tcl. Here in tcl file am just calling the python file and print the python response data which is in dict format. Can you please help me how to manuplate the python dictionary to tcl keyed list format. Or else is there any python or tcl library package is available to covert from dict to keyed list? Please share your ideas...

sample.py

def f1() :
        d = {}
        d["name"] = "Justin"
        d["Company"] = "AAA"
        d["doj"] = 2015
        print(d)
f1()

test.tcl

#! /usr/bin/tclsh
proc call_python {} {
    set output [exec python sample.py]
    puts $output
}

call_python

output : {'name': 'Justin', 'Company': 'AAA', 'doj': 2015}

Upvotes: 1

Views: 1625

Answers (2)

wiredawg
wiredawg

Reputation: 48

UPDATE: Added curly braces to support keys with spaces.

In tcl a keyed list (dict) is any string with an even number of tokens so this can be done simply by printing the key-value pairs sequentially.

sample.py

def f1() :
    d = {}
    d["name"] = "Justin"
    d["Company"] = "AAA"
    d["doj"] = 2015
    print " ".join(["{%s} {%s}" % (k,v) for k,v in d.items()])

test.tcl

#! /usr/bin/tclsh
proc call_python {} {
    set output [exec python sample.py]
    puts [dict keys $output]
    puts [dict get $optput name]
}

call_python

This will output:

name Company doj
Justin

Upvotes: 1

Donal Fellows
Donal Fellows

Reputation: 137717

You're advised to use a language-independent serialisation format for data interchange; like that, you get to use an existing library for doing the transformation and there's quite a few that are very well tested on both sides.

JSON's pretty good for this task. On the Python side:

import json

def f1():
    d = {}
    d["name"] = "Justin"
    d["Company"] = "AAA"
    d["doj"] = 2015
    print(json.dumps(d))
f1()

On the Tcl side (using the highly recommended rl_json package):

#! /usr/bin/tclsh
package require rl_json

proc call_python {} {
    set output [exec python sample.py]
    # Example of parsing the JSON
    set unpacked {}
    foreach key {name Company doj} {
        dict set unpacked [string tolower $key] [json get $output $key]
    }
    return $unpacked
}

# Print the parsed value out
puts [call_python]

However, in this case the object is very simple and the much smaller package in Tcllib for parsing JSON might also be good enough:

#! /usr/bin/tclsh
package require json

proc call_python {} {
    set output [exec python sample.py]
    return [json::json2dict $output]
}

# Print the parsed value out
puts [call_python]

The version with the rl_json package is strongly preferred for more complex documents.

Upvotes: 2

Related Questions