Multi Value Dictionary

Multi Value Dictionary?

It doesn't exist, but you can build one pretty quickly from Dictionary and List:

class MultiDict<TKey, TValue>  // no (collection) base class
{
private Dictionary<TKey, List<TValue>> _data = new Dictionary<TKey,List<TValue>>();

public void Add(TKey k, TValue v)
{
// can be a optimized a little with TryGetValue, this is for clarity
if (_data.ContainsKey(k))
_data[k].Add(v);
else
_data.Add(k, new List<TValue>() { v}) ;
}

// more members
}

Multi value Dictionary

Just create a Pair<TFirst, TSecond> type and use that as your value.

I have an example of one in my C# in Depth source code. Reproduced here for simplicity:

using System;
using System.Collections.Generic;

public sealed class Pair<TFirst, TSecond>
: IEquatable<Pair<TFirst, TSecond>>
{
private readonly TFirst first;
private readonly TSecond second;

public Pair(TFirst first, TSecond second)
{
this.first = first;
this.second = second;
}

public TFirst First
{
get { return first; }
}

public TSecond Second
{
get { return second; }
}

public bool Equals(Pair<TFirst, TSecond> other)
{
if (other == null)
{
return false;
}
return EqualityComparer<TFirst>.Default.Equals(this.First, other.First) &&
EqualityComparer<TSecond>.Default.Equals(this.Second, other.Second);
}

public override bool Equals(object o)
{
return Equals(o as Pair<TFirst, TSecond>);
}

public override int GetHashCode()
{
return EqualityComparer<TFirst>.Default.GetHashCode(first) * 37 +
EqualityComparer<TSecond>.Default.GetHashCode(second);
}
}

One Key to multiple values dictionary in C#?

A dictionary is a key-value pair, where the value is fetched depending on the key. The keys are all unique.

Now if you want a Dictionary with 1 keytype and multiple value types, you have a few options:

first is to use a Tuple

var dict = new Dictionary<KeyType, Tuple<string, string, bool, int>>()

The other is to use (with C# 4.0 and above):

var dict = new Dictionary<KeyType, dynamic>()

the System.Dynamic.ExpandoObject can have value of any type.

using System;
using System.Linq;
using System.Collections.Generic;

public class Test {
public static void Main(string[] args) {
dynamic d1 = new System.Dynamic.ExpandoObject();
var dict = new Dictionary<int, dynamic>();
dict[1] = d1;
dict[1].FooBar = "Aniket";
Console.WriteLine(dict[1].FooBar);
dict[1].FooBar = new {s1="Hello", s2="World", s3=10};
Console.WriteLine(dict[1].FooBar.s1);
Console.WriteLine(dict[1].FooBar.s3);
}
}

How to merge multiple values in a same dictionary?

One-liner

my_list = [[j for s in x[i] for j in y[s]] for i in x]

Longer but perhaps more readable

x = {1: [1,2], 2: [2,3], 3: [3,4], 4: [2,5]}

y = {1: [0,1], 2: [2,3], 3: [4,5], 4: [6,7], 5: [29,30,31]}

my_list = []

for i in x:
temp = []
my_list.append(temp)
for j in x[i]:
temp.extend(y[j])

print(my_list)

For complicated list comprehensions I prefer explicitly writing out loops for improved readability. Whether one snippet is more readable than another is of course a matter of opinion.

Output

[[0, 1, 2, 3], [2, 3, 4, 5], [4, 5, 6, 7], [2, 3, 29, 30, 31]]

I hope it helps. If there are any questions or if this is not what you wanted, please let me know!

How to add multiple values in dictionary for a key

here if you want to add multiple numbers

a_list = []
a_dict = {'Number': a_list}

#here so the will loop will be runing
RUN = True

while RUN:
a = int(input('Enter a number: '))
l = a_list.append(a)
quit_the_while = input('Enter q to quit or any thing to add more number: ')
if 'q' in quit_the_while:
break
else:
continue

print(a_dict)

here for 3 numbers only

a_list = []
a_dict = {'Number': a_list}

while len(a_list) < 3:
a = int(input('Enter a number: '))
l = a_list.append(a)

print(a_dict)

C# Multiple Keys with Multiple Values in Dictionary and postprocess the Dictonary

I think the following code should work for you:

// Test data to mock data from the CSV file
static IEnumerable<(string key, double value)> ReadCsv() =>
new[]
{
("ABC", 42.0),
("ABC", 123.0),
("DEF", 35.0),
("DEF", 15.0)
};

static void Main(string[] args)
{
// Task 1: Constructing a Dictionary<string, List<double>>
var data = ReadCsv()
.GroupBy(entry => entry.key)
.ToDictionary(
group => group.Key,
group => group.Select(entry => entry.value));

// Task 2: Iterating through the keys and verifying the total
var isSuccess = data.All(entry => entry.Value.Sum() > 50);
if (isSuccess)
Console.WriteLine("The total of values for each and every entry is greater than 50");
else
Console.WriteLine("The total of values for each and every entry is not greater than 50");
}

To read data from a CSV file, I would suggest using something like:

static IEnumerable<(string key, double value)> ReadCsv(string filePath, uint nHeaderLines = 0)
{
using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
using (var reader = new StreamReader(stream))
{
var lineIndex = 0u;
while (reader.ReadLine() is string dataEntry)
{
if (lineIndex++ < nHeaderLines // Skip header
|| string.IsNullOrWhiteSpace(dataEntry)) // Ignore blank lines
{
continue;
}

var dataElements = dataEntry.Split(',', StringSplitOptions.RemoveEmptyEntries);
var key = dataElements[0];
var value = double.Parse(dataElements[7], NumberStyles.Float, NumberFormatInfo.InvariantInfo);

yield return (key, value);
}
}
}

Please note, that for the real solution it would also make sense to check the data line if it has all the entries, i.e., that elements at index 0 and 7 always exist and are valid

Print dictionary with multiple values seperated

you can use 2 for loops to first iterate on keys and value (dictionary) and the 2nd one to iterate on the set (dictionary values).

mydict = {'bob': {"flying pigs"}, 'sam':{"open house", "monster dog"}, 'sally':{"glad smile"}}

for key, value in mydict.items():
for item in value:
print(key, item, sep=', ')

Output:

bob, flying pigs
sam, open house
sam, monster dog
sally, glad smile

How to get multiple dictionary values?

Use a for loop:

keys = ['firstKey', 'secondKey', 'thirdKey']
for key in keys:
myDictionary.get(key)

or a list comprehension:

[myDictionary.get(key) for key in keys]


Related Topics



Leave a reply



Submit