Python 3 (1) Dictionary Python Upper Case Values Present In A Single Key. (2) Why Datatype Sets In Python Does Not Return True Element?
Solution 1:
(1)
d2 = {key:[name.upper() for name in names] for key, names in d.items()}
(2)
That seems to be because True == 1
yields True
, which is what the Set uses to check if the value added is already in the Set and therefore has to be ignored.
Solution 2:
Your attempt is:
d.update((k, v.upper()) for k,v in d.items())
That doesn't work that way. For instance, v
is a list
, you cannot upper
a list...
This kind of transformation is better done using a dictionary comprehension to rebuild a new version of d
. You can do the upper part for each value using list comprehension:
d = {k:[v.upper() for v in vl] for k,vl in d.items()}
For your second question: since 1==True
, the set
keeps only the first inserted, which here is 1
. but could have been True
: example:
>>>{True,1}
{1}
>>>{True,1,True}
{True}
>>>{1,True}
{True}
>>>
more deterministic: pass a list
to build the set
instead of using the set
notation:
>>>set([True,1])
{True}
>>>set([1,True])
{1}
Solution 3:
(1) Could be shorter, just in one line as shown by others answers, but here is trade off between complexity and "Pythonicity":
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) Because True == 1
is true and Python set objects just have items that are differences between them.
Post a Comment for "Python 3 (1) Dictionary Python Upper Case Values Present In A Single Key. (2) Why Datatype Sets In Python Does Not Return True Element?"