How to Create Dictionary That Can Hold Anything in Key? or All the Possible Type It Capable to Hold

How do I create a Dictionary that holds different types in C#

Well, you could use Dictionary<string, dynamic> in C# 4 / .NET 4 - but other than that, you can't do it with exactly the code shown because there's no type which is implicitly convertible to int, string and double. (You could write your own one, but you'd have to list each type separately.)

You could use Dictionary<string, object> but then you'd need to cast the results:

int a = (int) Storage.Get("age");
string b = (string) Storage.Get("name");
double c = (double) Storage.Get("bmi");

Alternatively, you could make the Get method generic:

int a = Storage.Get<int>("age");
// etc

Define dictionary without Types gives compiler error in Swift

In your example, b is of type NSDictionary, which is immutable. Therefore you get an error when trying to modify its contents.

You need to declare b as an NSMutableDictionary to make this work:

let dictionary: NSMutableDictionary = [:]
dictionary["key"] = "value" // No errors.

What does Protocol ... can only be used as a generic constraint because it has Self or associated type requirements mean?

Protocol Observing inherits from protocol Hashable, which in turn inherits from protocol Equatable. Protocol Equatable has the following requirement:

func ==(lhs: Self, rhs: Self) -> Bool

And a protocol that contains Self somewhere inside it cannot be used anywhere except in a type constraint.

Here is a similar question.

how to make a dictionary that can hold more than 1 data?

Dictionary<> is created in a such way that you can access Key Value pair in most efficient way. Now in Dictionary<> you can not have two pairs with same key. To do so,
what you can do, you create a dictionary like Dictionary<char, List<bool[]>>, now in this dictionary you can store one key with more than one value.

Update

If you change the dictionary to Dictionary<char, List<bool[]>> then to store one key with more than one value you will have to as follows

private bool[] downsampled;
private Dictionary<char, List<bool[]>> letterData = new Dictionary<Char, List<bool[]>>();

//
// Your Code
//

if (Result != null)
{
Result = Result.ToUpper();
if (Result.Length == 0)
{
MessageBox.Show("Please enter a character.");
}
else if (Result.Length < 1)
{
MessageBox.Show("Please enter only a single character.");
}
else
{
if (this.letterData.ContainsKey(Result[0]))
{
this.letterData[Result[0]].Add(this.downsampled);
}
else
{
this.letterData.Add(Result[0], new List<bool[]>() { this.downsampled });
}
this.letters.Items.Add(Result);
this.ClearEntry();
}
}

If you want to string as key, instead of char, use Dictionary<string, List<bool[]>>.

Hope this answers your question.

What can you use as keys in a C# dictionary?

The requirement for a dictionary key is that it is comparable and hashable. That's turtles all the way down in .NET, every type (other than pointer types) derives from System.Object and it is always comparable thanks to its Equals() method. And hashable thanks to its GetHashCode() method. So any .NET type automatically can be used as a key.

If you want to use your own type as the key then you only need to do something special if you want to re-define object identity. In other words, if you need the ability for two distinct objects to be equal. You'd then override the Equals() method, typically comparing fields of the object. And then you must also override GetHashCode(), equal objects must generate the same hash code.

If the type cannot be changed or you want to customize the behavior especially for the Dictionary then you can pass a custom IEqualityComparer<> to the constructor. Keep in mind that the quality of the hash code you generate with your own GetHashCode() determines the dictionary efficiency.

How can I iterate over all possible values of a dictionary?

Here is a concise approach using itertools.product and recursion:

from itertools import product

def traverse(d):
K,V = zip(*d.items())
for v in product(*(v if isinstance(v,list) else traverse(v) for v in V)):
yield dict(zip(K,v))

Sample run:

>>> d = {
>>> "key0": {
>>> "key1": [1, 2],
>>> "key2": [8, 9, 10]
>>> },
>>> "key3": [22, 23, 24]
>>> }

>>> from pprint import pprint
>>> pprint([*traverse(d)])
[{'key0': {'key1': 1, 'key2': 8}, 'key3': 22},
{'key0': {'key1': 1, 'key2': 8}, 'key3': 23},
{'key0': {'key1': 1, 'key2': 8}, 'key3': 24},
{'key0': {'key1': 1, 'key2': 9}, 'key3': 22},
{'key0': {'key1': 1, 'key2': 9}, 'key3': 23},
{'key0': {'key1': 1, 'key2': 9}, 'key3': 24},
{'key0': {'key1': 1, 'key2': 10}, 'key3': 22},
{'key0': {'key1': 1, 'key2': 10}, 'key3': 23},
{'key0': {'key1': 1, 'key2': 10}, 'key3': 24},
{'key0': {'key1': 2, 'key2': 8}, 'key3': 22},
{'key0': {'key1': 2, 'key2': 8}, 'key3': 23},
{'key0': {'key1': 2, 'key2': 8}, 'key3': 24},
{'key0': {'key1': 2, 'key2': 9}, 'key3': 22},
{'key0': {'key1': 2, 'key2': 9}, 'key3': 23},
{'key0': {'key1': 2, 'key2': 9}, 'key3': 24},
{'key0': {'key1': 2, 'key2': 10}, 'key3': 22},
{'key0': {'key1': 2, 'key2': 10}, 'key3': 23},
{'key0': {'key1': 2, 'key2': 10}, 'key3': 24}]


Related Topics



Leave a reply



Submit