-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
  • 73,857
  • 44
  • 240
  • 251
Vaibhav Sinha
  • 67
  • 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,027
  • 2
  • 11
  • 23
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
  • 19,475
  • 3
  • 34
  • 50
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
  • 131,796
  • 23
  • 122
  • 195