12

Is there a good way in C# to mimic the following python syntax:

mydict = {}
mydict["bc"] = {}
mydict["bc"]["de"] = "123";  # <-- This line
mydict["te"] = "5";          # <-- While also allowing this line

In other words, I'd like something with [] style access that can return either another dictionary or a string type, depending on how it has been set.

I've been trying to work this out with a custom class but can't seem to succeed. Any ideas?

Thanks!

Edit: I'm being evil, I know. Jared Par's solution is great . . . for a 2-level dictionary of this form. However, I am also curious about further levels . . . for instance,

mydict["bc"]["df"]["ic"] = "32";

And so on. Any ideas about that?

Edit 3:

Here is the final class I ended up using:

class PythonDict {
    /* Public properties and conversions */
    public PythonDict this[String index] {
        get {
            return this.dict_[index];
        }
        set {
            this.dict_[index] = value;
        }
    }

    public static implicit operator PythonDict(String value) {
        return new PythonDict(value);
    }

    public static implicit operator String(PythonDict value) {
        return value.str_;
    }

    /* Public methods */
    public PythonDict() {
        this.dict_ = new Dictionary<String, PythonDict>();
    }

    public PythonDict(String value) {
        this.str_ = value;
    }

    public bool isString() {
        return (this.str_ != null);
    }

    /* Private fields */
    Dictionary<String, PythonDict> dict_ = null;
    String str_ = null;
}

This class works for infinite levels, and can be read from without explicit conversion (dangerous, maybe, but hey).

Usage like so:

        PythonDict s = new PythonDict();
        s["Hello"] = new PythonDict();
        s["Hello"]["32"] = "hey there";
        s["Hello"]["34"] = new PythonDict();
        s["Hello"]["34"]["Section"] = "Your face";
        String result = s["Hello"]["34"]["Section"];
        s["Hi there"] = "hey";

Thank you very much Jared Par!

2 Answers 2

14

You can achieve this by having the class, lets call it PythonDictionary, which is returned from mydict["bc"] have the following members.

  • A indexer property to allow for the ["de"] access
  • A implicit conversion from string to PythonDictionary

That should allow both cases to compile just fine.

For example

public class PythonDictionary {
    public string this[string index] {
        get { ... }
        set { ... }
    }
    public static implicit operator PythonDictionary(string value) {
        ...
    }
}

public void Example() {
    Dictionary<string, PythonDictionary> map = new Dictionary<string, PythonDictionary>();
    map["42"]["de"] = "foo";
    map["42"] = "bar";
}
3
  • Very nicely done. I hate these implicit conversions, but it certainly lets you do what the OP wants. Sep 4, 2009 at 20:37
  • 1
    Great solution for 1 or 2 keys . . . I like it for that, and it would probably work in my case (so thank you very much!). However, I am also curious about deeper dictionaries. Any ideas there?
    – Walt W
    Sep 4, 2009 at 20:43
  • Yup, it was very much extendible. Resulting class is shown in question. Thank you very much!
    – Walt W
    Sep 4, 2009 at 21:01
2

Thanks for posting this question and resolution. Converted to VB.NET:

Public Class PythonDict
    ' Public properties and conversions
    Default Public Property Item(ByVal index As String) As PythonDict
        Get
            Return Me.dict_(index)
        End Get

       Set(value As PythonDict)
            Me.dict_(index) = value
       End Set
    End Property

    Public Shared Narrowing Operator CType(value As String) As PythonDict
       Return New PythonDict(value)
    End Operator

    Public Shared Widening Operator CType(value As PythonDict) As String
       Return value.str_
    End Operator

    ' Public methods
    Public Sub New()
       Me.dict_ = New Dictionary(Of String, PythonDict)()
    End Sub

    Public Sub New(value As String)
       Me.str_ = value
    End Sub

    Public Function isString() As Boolean
       Return (Me.str_ IsNot Nothing)
    End Function

    ' Private fields
    Private dict_ As Dictionary(Of String, PythonDict) = Nothing
    Private str_ As String = Nothing
End Class

Usage:

Dim s As PythonDict = New PythonDict()
s("Hello") = New PythonDict()
s("Hello")("32") = "hey there"
s("Hello")("34") = New PythonDict()
s("Hello")("34")("Section") = "Your face"
Dim result As String = s("Hello")("34")("Section")
s("Hi there") = "hey"
3
  • This answer doesn't quite fit into Stack Overflow's policy (and got flagged as such), because it doesn't answer the OP's question (about C#.) but I think it adds value. I'm recommending it not be deleted. Do note, however, that someone looking for a VB-only solution might not think to check this question.
    – jpaugh
    Feb 6, 2018 at 23:52
  • 1
    Just trying to contribute. Feb 9, 2018 at 2:46
  • @jmjhonson85 I respect that. I read your answer in a review queue, because it was flagged. I'm just hoping to give you the lay of the land, so to speak.
    – jpaugh
    Feb 9, 2018 at 19:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.