Understanding with multiple input sets

I am experimenting with python and getting stuck trying to understand error messages in the context of what I'm doing.

I play with understanding and try to find a template for creating an understanding of a list / dictionary with more than one set of input (if possible):

Note: Here, a set of input words means an understanding input area. In setbuilder notation, where python came up with its interpretations [Y for X in LIST], Y is the output function, X is the variable, and LIST is the set of input.

Suppose I have the following working code:

from random import randint mydict = {k: 0 for k in range(10)} result = {randint(0,9): v + 1 for v in mydict.values()} 

I am not trying to do something special. This is not even useful code, because it will not work as expected. All elements in the dictionary will have a value of 1, and not just those pointed to by a random generator. My only goal is to get the foundation from where I start my attempt to work with a tuple of input sets.

 from random import randint mydict = {k: 0 for k in range(10)} result = {k: v + 1 for k, v in (randint(0,9), mydict.values())} 

This parameter gives me: TypeError: 'int' object is not iterable .

Replacing the input sets and unpacking, I:

 result = {k: v + 1 for *v, k in (mydict.values(), randint(0,9))} 

But this option gives me: TypeError: can only concatenate list (not "int") to list

Do these errors appear because I'm trying to do something that the language grammar does not understand, or am I missing something, and could I really fix the code?

+5
source share
1 answer

You will need to create a separate understanding of random numbers, because it is currently worth it, you only have one random number. In addition, you will need to pin the results to get the combined object:

 >>> from random import randint >>> mydict = {k: 0 for k in range(10)} >>> result = {k: v + 1 for k, v in zip([randint(0,9) for _ in range(10)] , mydict.values())} >>> result {2: 1, 3: 1, 4: 1, 5: 1, 8: 1, 9: 1} 

Note that since your original dict has a value of 0 for all of its keys, all the values ​​in the dict result are 1 ( 0+1 ).

In addition, since we make the keys random, possible overlaps are possible (say, 2 was generated twice), so we do not see all the keys in the result dictionary.

As @wim notes in the comments below, the best way to create this dictionary would be to use:

 >>> {randint(0,9): v+1 for v in mydict.values()} {0: 1, 1: 1, 2: 1, 3: 1, 6: 1, 7: 1} 
+7
source

All Articles