Which is the best way to make a dictionary of lists? For instance, if I have lists list1, list2 and want to make a dictionary my_dict like that:
my_dict = ['list1': list1, 'list2': list2]
I've found this example but the best answer is written in 2009. Maybe there are some new more laconic ways to do this?
In Python dictionary, it is an unordered and immutable data type and can be used as a keys element. To create a dictionary of lists, first, we insert key-value within the curly brackets and to obtain the values of a dictionary, and then use the key name within the square brackets.
The keys are immutable. Just like lists, the values of dictionaries can hold heterogeneous data i.e., integers, floats, strings, NaN, Booleans, lists, arrays, and even nested dictionaries.
By using zip() and dict() method The zip() method takes multiple iterable objects as arguments such as lists and tuples and returns an iterator. In Python, the dict() method creates an empty dictionary. In this example, the dict and zip() method join together to convert lists into dictionaries.
The methods dict. keys() and dict. values() return lists of the keys or values explicitly. There's also an items() which returns a list of (key, value) tuples, which is the most efficient way to examine all the key value data in the dictionary.
You need to use curly rather than square brackets, but otherwise this is probably as good as it gets:
list1 = ['a', 'b', 'c']
list2 = [1, 2, 3, 4]
my_dict = {'list1': list1, 'list2': list2}
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