C# 4.0 从C访问Ironpython字典#

C# 4.0 从C访问Ironpython字典#,c#-4.0,ironpython,C# 4.0,Ironpython,我在Ironpython脚本中定义了字典,我想从我的C#访问这个字典 代码。有人能提供示例代码来满足我的要求吗 很抱歉,之前我没有提到我的代码问题声明 import clr clr.AddReference("System.Core") import System clr.ImportExtensions(System.Linq) from System.Collections.Generic import Dictionary,List def check(self): dict1

我在Ironpython脚本中定义了字典,我想从我的C#访问这个字典 代码。有人能提供示例代码来满足我的要求吗

很抱歉,之前我没有提到我的代码问题声明

import clr
clr.AddReference("System.Core")
import System
clr.ImportExtensions(System.Linq)
from System.Collections.Generic import Dictionary,List

def check(self):
    dict1 = Dictionary[str,str]
    dict1["a"] = "aa"
    dict2 = Dictionary[str,str]
    dict2["b"] = "bb"
    self[0] = dict1
#   self.Add(dict1)
    return self
C#

var runtime=Python.CreateRuntime();
动态测试=runtime.UseFile(“test.py”);
var myDictList=新列表();
var myDL=新列表();
myDL=测试检查(myDictList);
我的目标是在python中对字典列表进行操作(添加、从列表中删除),并将其发送回C#,以便进一步使用。 我想要的是用python或C语言创建一个字典列表,并在这两个地方(python和C)使用它。 我如何才能做到这一点。

这项功能:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Scripting.Hosting;
using Microsoft.Scripting.Utils;
using Microsoft.Scripting.Runtime;
using IronPython;
using IronPython.Hosting;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            ScriptEngine pyEngine = Python.CreateEngine();
            ScriptScope pyScope = pyEngine.CreateScope();
            ScriptSource pyScript = pyEngine.CreateScriptSourceFromString("d = {'a':1,'b':2,'c':3}");
            CompiledCode pyCompiled = pyScript.Compile();
            pyCompiled.Execute(pyScope);
            IronPython.Runtime.PythonDictionary d = pyScope.GetVariable("d");
            Console.WriteLine(d.get("a"));
            Console.Read();
        }
    }
}
应该为键“a”提供第一个值。希望这能让你走。 可能有一个或两个包含太多

def check(self):
    dict1 = Dictionary[str,str]()
    dict1["a"] = "aa"
    dict2 = Dictionary[str,str]()
    dict2["b"] = "bb"
    self[0] = dict1
    #   self.Add(dict1)
    return self

注意()。例如,在C#中不能有混合类型。使用
IronPython.Runtime.PythonDictionary
作为数据类型有什么问题?您可以使用
pyScope.SetVariable
设置数据,也可以获取数据。在python中,我正在编写一个解析器,它将文件路径作为输入,并创建一个已解析项的字典列表。然后我想在C#中使用解析数据。所以我不认为pyScope.SetVariable或pyScope.GetVariable对我有帮助,因为在C#中,我没有修改任何东西,我只是使用解析的内容。你试过我的小代码snipplet吗?我确实使用了CreateScriptSourceFromString,但您也可以将python脚本文件作为输入。d是字典。它有条目a:1B:2和c:3。我访问了a,得到了1。这不正是你想要的吗?另外,您还可以使用Xml.Serializer对词典进行序列化,并再次用C#读回。这将克服python字典和泛型字典之间的不兼容性。
def check(self):
    dict1 = Dictionary[str,str]()
    dict1["a"] = "aa"
    dict2 = Dictionary[str,str]()
    dict2["b"] = "bb"
    self[0] = dict1
    #   self.Add(dict1)
    return self