-1

(1) A snippet that takes a dictionary and uppercases every value in the dictionary and sets that value back into the dictionary at the same key e.g.

Given:

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

Result:

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

(2) Why datatype SET does not return TRUE element when printed? Eg. {'hi', 1, True} returns only {'hi', 1}

For (1) I am using something like this:

 d = {'a': ['amber', 'ash'], 'b': ['bart', 'betty']} 
 d.update((k, v.upper()) for k, v in d.items())
Krunal
  • 77,632
  • 48
  • 245
  • 261
Vaibhav Sinha
  • 67
  • 1
  • 2
  • 10

3 Answers3

3

(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.

Jeronimo
  • 2,268
  • 2
  • 13
  • 28
1

(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.

Rolf of Saxony
  • 21,661
  • 5
  • 39
  • 60
1

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}
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219