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 :-))
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.
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.
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.
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.
The Enumerable
class has a nice class extension for the IEnumerable<>
: Try
var myDictionary = myList.ToDictionary(key => key.property1, value => value.property2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With