using System;
namespace Python.Runtime
{
///
/// Represents a Python dictionary object. See the documentation at
/// PY2: https://docs.python.org/2/c-api/dict.html
/// PY3: https://docs.python.org/3/c-api/dict.html
/// for details.
///
public class PyDict : PyObject
{
///
/// PyDict Constructor
///
///
/// Creates a new PyDict from an existing object reference. Note
/// that the instance assumes ownership of the object reference.
/// The object reference is not checked for type-correctness.
///
public PyDict(IntPtr ptr) : base(ptr)
{
}
///
/// PyDict Constructor
///
///
/// Creates a new Python dictionary object.
///
public PyDict() : base(Runtime.PyDict_New())
{
if (obj == IntPtr.Zero)
{
throw new PythonException();
}
}
///
/// PyDict Constructor
///
///
/// Copy constructor - obtain a PyDict from a generic PyObject. An
/// ArgumentException will be thrown if the given object is not a
/// Python dictionary object.
///
public PyDict(PyObject o) : base(o.obj)
{
Runtime.XIncref(o.obj);
if (!IsDictType(o))
{
throw new ArgumentException("object is not a dict");
}
}
///
/// IsDictType Method
///
///
/// Returns true if the given object is a Python dictionary.
///
public static bool IsDictType(PyObject value)
{
return Runtime.PyDict_Check(value.obj);
}
///
/// HasKey Method
///
///
/// Returns true if the object key appears in the dictionary.
///
public bool HasKey(PyObject key)
{
return Runtime.PyMapping_HasKey(obj, key.obj) != 0;
}
///
/// HasKey Method
///
///
/// Returns true if the string key appears in the dictionary.
///
public bool HasKey(string key)
{
using (var str = new PyString(key))
{
return HasKey(str);
}
}
///
/// Keys Method
///
///
/// Returns a sequence containing the keys of the dictionary.
///
public PyObject Keys()
{
IntPtr items = Runtime.PyDict_Keys(obj);
if (items == IntPtr.Zero)
{
throw new PythonException();
}
return new PyObject(items);
}
///
/// Values Method
///
///
/// Returns a sequence containing the values of the dictionary.
///
public PyObject Values()
{
IntPtr items = Runtime.PyDict_Values(obj);
if (items == IntPtr.Zero)
{
throw new PythonException();
}
return new PyObject(items);
}
///
/// Items Method
///
///
/// Returns a sequence containing the items of the dictionary.
///
public PyObject Items()
{
var items = Runtime.PyDict_Items(this.obj);
try
{
if (items.IsNull())
{
throw new PythonException();
}
return items.MoveToPyObject();
}
finally
{
items.Dispose();
}
}
///
/// Copy Method
///
///
/// Returns a copy of the dictionary.
///
public PyDict Copy()
{
IntPtr op = Runtime.PyDict_Copy(obj);
if (op == IntPtr.Zero)
{
throw new PythonException();
}
return new PyDict(op);
}
///
/// Update Method
///
///
/// Update the dictionary from another dictionary.
///
public void Update(PyObject other)
{
int result = Runtime.PyDict_Update(obj, other.obj);
if (result < 0)
{
throw new PythonException();
}
}
///
/// Clear Method
///
///
/// Clears the dictionary.
///
public void Clear()
{
Runtime.PyDict_Clear(obj);
}
}
}