简体   繁体   中英

How to convert Iron Python dictionary to Python dictionary

I need to convert a received IronPython dictionary variable to a regular Python dictionary. From what I understand the variable is so-called:

'System.Collections.Generic.Dictionary`2[System.String,System.String]'

If I use:

for each in IronDictionary:
    print type(each)
    print each

I am getting:

type: '<class 'System.Collections.Generic.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'>'
'[MultiProcess, False]' # this line is a result of `print each` command

So in an essence each is just like a regular Python list... It would be great if I could convert this entire Iron dictionary to a regular Python one. If it is not possible, I wouldn't mind to iterate using for each in IronDict: and converting every Iron each into a regular Python list or a Python string maybe?... How to accomplish this correctly?

I can only suspect what you are asking for. Assuming your dictionary uses string as key and value, if you would like to create python dictionary from clr one, try:

pythondict = dict(clrdict)

And reverse direction:

from System.Collections.Generic import Dictionary
clrdict = Dictionary[str,str](pythondict)

You may also just try to use it as-is without converting. Can you show why do you need a conversion?

EDIT: This is working example:

from System.Collections.Generic import Dictionary
clrdict = Dictionary[str,str]()
clrdict.Add('k1','v1')
clrdict.Add('k2','v2')
pythondict=dict(clrdict)

print clrdict
print type(clrdict)
print pythondict
print type(pythondict)

Which produces:

Dictionary[str, str]({'k1' : 'v1', 'k2' : 'v2'})
<type 'Dictionary[str, str]'>
{'k2': 'v2', 'k1': 'v1'}
<type 'dict'>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM