Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create and initialize dictionary from list

Tags:

c#

linq

Is there a way to combine below two statements into one, so you can create and initialize a dictionary from an array in one single statement?

var myDictionary = new Dictionary<int, string>();
myList.ForEach(i => myDictionary.Add(i.property1, i.property2));

(whether or not that makes the code easier to read is another topic :-))

like image 548
Peter Avatar asked Sep 20 '16 12:09

Peter


People also ask

Can you create a dictionary from a list?

To convert a list to a dictionary using the same values, you can use the dict. fromkeys() method. To convert two lists into one dictionary, you can use the Python zip() function. The dictionary comprehension lets you create a new dictionary based on the values of a list.

How do you initialize a dictionary?

Initialization. Dictionaries are also initialized using the curly braces {} , and the key-value pairs are declared using the key:value syntax. You can also initialize an empty dictionary by using the in-built dict function. Empty dictionaries can also be initialized by simply using empty curly braces.

How do you declare and initialize a dictionary in Python?

Another way to initialize a python dictionary is to use its built-in “dict()” function in the code. So, you have to declare a variable and assign it the “dict()” function as an input value. After this, the same print function is here to print out the initialized dictionary.

How do you create a value from a dictionary list?

To convert dictionary values to list sorted by key we can use dict. items() and sorted(iterable) method. Dict. items() method always returns an object or items that display a list of dictionaries in the form of key/value pairs.


1 Answers

The Enumerable class has a nice class extension for the IEnumerable<>: Try

var myDictionary = myList.ToDictionary(key => key.property1, value => value.property2);
like image 71
Jeroen van Langen Avatar answered Sep 29 '22 11:09

Jeroen van Langen