PYTHON 3 (1) Vocabulary Python uppercase value is present in one key. (2) Why python dataset does not return True?

(1) A fragment that takes a dictionary and upper case of each value in a dictionary and sets that value back to the dictionary on the same key, for example.

Given:

d = {'a': ['amber', 'ash'], 'b': ['bart', 'betty']} 

Result:

 {'a': ['AMBER', 'ASH'], 'b': ['BART', 'BETTY']} 

(2) Why does datatype SET not return a TRUE element when printing? For example. {'hi', 1, True} returns only {'hi', 1}

For (1) I use something like this:

  d = {'a': ['amber', 'ash'], 'b': ['bart', 'betty']} d.update((k, v.upper()) for k, v in d.items()) 
0
python
Sep 01 '17 at 15:43 on
source share
3 answers

(one)

 d2 = {key:[name.upper() for name in names] for key, names in d.items()} 

(2)

It seems that because True == 1 gives True , this is what Set uses to check if the added value is added to Set, and therefore should be ignored.

+3
Sep 01 '17 at 15:49
source share

(1) It may be shorter, in just one line, as other answers show, but there is a trade-off between complexity and "Pythonity":

 d = {'a': ['amber', 'ash'], 'b': ['bart', 'betty']} for k in d: d[k] = [i.upper() for i in d[k]] print(d) 

OUTPUT:

 {'a': ['AMBER', 'ASH'], 'b': ['BART', 'BETTY']} 

(2) Since True == 1 is true, and objects with a Python installation only have elements that are the differences between them.

+1
Sep 01 '17 at 15:48
source share

Your attempt:

 d.update((k, v.upper()) for k,v in d.items()) 

This does not work. For example, v is list , you cannot upper list ...

This kind of conversion is best done using dictionary understanding to rebuild the new version of d . You can do the top for each value using a list comprehension:

 d = {k:[v.upper() for v in vl] for k,vl in d.items()} 

For your second question: starting from 1==True , set only stores the first inserted, which is 1 here. but can be True : example:

 >>> {True,1} {1} >>> {True,1,True} {True} >>> {1,True} {True} >>> 

more deterministic: pass a list to build a set instead of the notation set :

 >>> set([True,1]) {True} >>> set([1,True]) {1} 
+1
01 Sep '17 at 15:52
source share



All Articles