Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - dictionary of lists

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?

like image 898
Elena Avatar asked Jan 04 '15 22:01

Elena


People also ask

Can you create a dictionary of lists in Python?

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.

Can a dictionary hold a list Python?

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.

How do I create a dictionary in multiple lists?

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.

How do you get a list of all the keys in a dictionary?

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.


1 Answers

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}
like image 168
NPE Avatar answered Oct 04 '22 04:10

NPE