C# way to mimic Python Dictionary Syntax
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!
Asked by: Arnold694 | Posted: 30-11-2021
Answer 1
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";
}
Answered by: Elise121 | Posted: 01-01-2022
Answer 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"
Answered by: Rebecca616 | Posted: 01-01-2022
Similar questions
python - Syntax - saving a dictionary as a csv file
I am trying to "clean up" some data - I'm creating a dictionary of the channels that I need to keep and then I've got an if block to create a second dictionary with the correct rounding.
Dictionary looks like this:
{'time, s': (imported array), 'x temp, C':(imported array),
'x pressure, kPa': (diff. imported array).....etc}
Each imported array is 1-d.
I was ...
Python Syntax Error with Dictionary
I am trying to do the following code:
while y < x:
data_list[y].title = title
data_list[y].link = link
data_list[y].description = description
story_list.update({title: link, description})
y += 1
Where x is len(data_list) and y = 0 outside the loop.
When I try to run it, I get a syntax error for '}' only (not on the '{' bracket though) on the dict...
Python 3: for loop syntax with dictionary
The following code snippet works:
param = {}
for nround_counter in [1,2,3]:
{
print(nround_counter)
#param = {'objective' : 'multi:softmax'}
}
But the following doesn't:
param = {}
for nround_counter in [1,2,3]:
{
print(nround_counter)
param = {'objective' : 'multi:softmax'}
}
The error given is inval...
Python Dictionary Syntax Error [learn python the hard way -ex39]
states = [
'Oregon': 'OR',
'Florida': 'FL',
'California': 'CA',
'New York': 'NY',
'Michigan': 'MI'
]
print states.Oregon
Why is this code showing syntax error in line 2?
Running on python 2.7.12 (default on ubuntu)
python - List all words in a dictionary that start with <user input>
How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string?
Ex:
User: "abd"
Program:abdicate, abdomen, abduct...
Thanks!
Edit: I'm using python, but I assume that this is a fairly language-independent problem.
python, dictionary and int error
I have a very frustrating python problem. In this code
fixedKeyStringInAVar = "SomeKey"
def myFunc(a, b):
global sleepTime
global fixedKeyStringInAVar
varMe=int("15")
sleepTime[fixedKeyStringInAVar] = varMe*60*1000
#more code
Now this works. BUT sometimes when I run this function I get
TypeError: 'int' object does not support item assignment
python - Best way to create a NumPy array from a dictionary?
I'm just starting with NumPy so I may be missing some core concepts...
What's the best way to create a NumPy array from a dictionary whose values are lists?
Something like this:
d = { 1: [10,20,30] , 2: [50,60], 3: [100,200,300,400,500] }
Should turn into something like:
data = [
[10,20,30,?,?],
[50,60,?,?,?],
[100,200,300,400,500]
]
...
python - List a dictionary
In a list appending is possible. But how I achieve appending in dictionary?
Symbols from __ctype_tab.o:
Name Value Class Type Size Line Section
__ctype |00000000| D | OBJECT|00000004| |.data
__ctype_tab |00000000| r | OBJECT|00000101| |.rodata
Symbols from _ashldi3.o:
Name Value Class ...
python - How to filter a dictionary by value?
Newbie question here, so please bear with me.
Let's say I have a dictionary looking like this:
a = {"2323232838": ("first/dir", "hello.txt"),
"2323221383": ("second/dir", "foo.txt"),
"3434221": ("first/dir", "hello.txt"),
"32232334": ("first/dir", "hello.txt"),
"324234324": ("third/dir", "dog.txt")}
I want all values that are equal to each other to be moved into...
Python and dictionary like object
I need a python 3.1 deep update function for dictionaries (a function that will recursively update child dictionaries that are inside a parent dictionary).
But I think, in the future, my function could have to deal with objects that behave like dictionaries but aren't. And furthermore I want to avoid using isinstance and type (because they are considered b...
python - Remove dictionary from list
If I have a list of dictionaries, say:
[{'id': 1, 'name': 'paul'},
{'id': 2, 'name': 'john'}]
and I would like to remove the dictionary with id of 2 (or name 'john'), what is the most efficient way to go about this programmatically (that is to say, I don't know the index of the entry in the list so it can't simply be popped).
python - Can a dictionary be passed to django models on create?
Is it possible to do something similar to this with a list, dictionary or something else?
data_dict = {
'title' : 'awesome title',
'body' : 'great body of text',
}
Model.objects.create(data_dict)
Even better if I can extend it:
Model.objects.create(data_dict, extra='hello', extra2='world')
python - Make Dictionary From 2 List
This question already has answers here:
Python dictionary simple way to add a new key value pair
Say you have,
foo = 'bar'
d = {'a-key':'a-value'}
And you want
d = {'a-key':'a-value','foo':'bar'}
e = {'foo':foo}
I know you can do,
d['foo'] = foo
#Either of the following for e
e = {'foo':foo}
e = dict(foo=foo)
But, in all these way to add the variable foo to dict, I have had to use the word foo twice; onc...
sorting - In Python, how can you easily retrieve sorted items from a dictionary?
Dictionaries unlike lists are not ordered (and do not have the 'sort' attribute). Therefore, you can not rely on getting the items in the same order when first added.
What is the easiest way to loop through a dictionary containing strings as the key value and retrieving them in ascending order by key?
For example, you had this:
d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'}
Python dictionary from an object's fields
Do you know if there is a built-in function to build a dictionary from an arbitrary object? I'd like to do something like this:
>>> class Foo:
... bar = 'hello'
... baz = 'world'
...
>>> f = Foo()
>>> props(f)
{ 'bar' : 'hello', 'baz' : 'world' }
NOTE: It should not include methods. Only fields.
python - How do you retrieve items from a dictionary in the order that they're inserted?
Is it possible to retrieve items from a Python dictionary in the order that they were inserted?
python - How can I make a dictionary from separate lists of keys and values?
I want to combine these:
keys = ['name', 'age', 'food']
values = ['Monty', 42, 'spam']
Into a single dictionary:
{'name': 'Monty', 'age': 42, 'food': 'spam'}
python - Dictionary or If statements, Jython
I am writing a script at the moment that will grab certain information from HTML using dom4j.
Since Python/Jython does not have a native switch statement I decided to use a whole bunch of if statements that call the appropriate method, like below:
if type == 'extractTitle':
extractTitle(dom)
if type == 'extractMetaTags':
extractMetaTags(dom)
Is a Python dictionary an example of a hash table?
One of the basic data structures in Python is the dictionary, which allows one to record "keys" for looking up "values" of any type. Is this implemented internally as a hash table? If not, what is it?
python - Is there a "one-liner" way to get a list of keys from a dictionary in sorted order?
The list sort() method is a modifier function that returns None.
So if I want to iterate through all of the keys in a dictionary I cannot do:
for k in somedictionary.keys().sort():
dosomething()
Instead, I must:
keys = somedictionary.keys()
keys.sort()
for k in keys:
dosomething()
Is there a pretty way to iterate t...
python - Interface to versioned dictionary
I have an versioned document store which I want to access through an dict like interface.
Common usage is to access the latest revision (get, set, del), but one should be able to access specific revisions too (keys are always str/unicode or int).
from UserDict import DictMixin
class VDict(DictMixin):
def __getitem__(self, key):
if isinstance(key, tuple):
docid, rev = key
e...
python - List all words in a dictionary that start with <user input>
How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string?
Ex:
User: "abd"
Program:abdicate, abdomen, abduct...
Thanks!
Edit: I'm using python, but I assume that this is a fairly language-independent problem.
python - Check if a given key already exists in a dictionary and increment it
How do I find out if a key in a dictionary has already been set to a non-None value?
I want to increment the value if there's already one there, or set it to 1 otherwise:
my_dict = {}
if my_dict[key] is not None:
my_dict[key] = 1
else:
my_dict[key] += 1
Still can't find your answer? Check out these communities...
PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python