如何将 Iron Python 字典转换为 Python 字典

alp*_*ric 2 python ironpython

我需要将接收到的 IronPython 字典变量转换为常规 Python 字典。据我所知,变量是所谓的:

'System.Collections.Generic.Dictionary`2[System.String,System.String]'
Run Code Online (Sandbox Code Playgroud)

如果我使用:

for each in IronDictionary:
    print type(each)
    print each
Run Code Online (Sandbox Code Playgroud)

我正进入(状态:

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

所以本质each上就像一个普通的 Python 列表……如果我能把整个 Iron 字典转换成一个普通的 Python 字典就好了。如果不可能,我不介意迭代使用for each in IronDict:每个 Ironeach并将其转换为常规 Python 列表或 Python 字符串?...如何正确完成此操作?

Paw*_*ski 7

我只能怀疑你在问什么。假设您的字典使用字符串作为键和值,如果您想从 clr one 创建 python 字典,请尝试:

pythondict = dict(clrdict)
Run Code Online (Sandbox Code Playgroud)

并反转方向:

from System.Collections.Generic import Dictionary
clrdict = Dictionary[str,str](pythondict)
Run Code Online (Sandbox Code Playgroud)

您也可以尝试按原样使用它而不进行转换。你能说明为什么需要转换吗?

编辑:这是工作示例:

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)
Run Code Online (Sandbox Code Playgroud)

其中产生:

Dictionary[str, str]({'k1' : 'v1', 'k2' : 'v2'})
<type 'Dictionary[str, str]'>
{'k2': 'v2', 'k1': 'v1'}
<type 'dict'>
Run Code Online (Sandbox Code Playgroud)