-1

in one of my assignment i was tasked to do this:

1 >>> d = {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 5}
2 >>> print ________
3 ['one', 'two', 'three', 'four']

how to only use one line of code in line 2 of the code above without importing any other functions to get the ouput ['one', 'two', 'three', 'four'] in line 3?

i can only print out all the values of the dictionary without excluding the last element using print(list(d.values())) and my result is ['one', 'two', 'three', 'four', 5]

Aaron Poh
  • 1
  • 4
  • 1
    Possible duplicate of [Understanding slice notation](https://stackoverflow.com/questions/509211/understanding-slice-notation) – yatu Feb 21 '19 at 11:21
  • 2
    prior to python 3.7 dicts were not guaranteed ordered so the *last* value is not really a thing. for later python versions you may slice the list – Chris_Rands Feb 21 '19 at 11:22

4 Answers4

3

In case you want to print only string dictionary values (which in the given example will exclude the last integer value), you can use list comprehension inside the print() and check if the dictionary value is of string type:

print([val for val in d.values() if type(val) == str])

This will also work if you had a dictionary like this:

d = {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 5, 6: 'six'}
print([val for val in d.values() if type(val) == str])
['one', 'two', 'three', 'four', 'six']
Andreas K.
  • 9,282
  • 3
  • 40
  • 45
0

one line answer:

list(d.values())[:-1]
Meysam
  • 596
  • 6
  • 12
0

d.values() is not subscriptable, so you need to cast it into a list. Then you can get the entire list minus the last element

print (list(d.values())[:-1])
Ron Serruya
  • 3,988
  • 1
  • 16
  • 26
0
print([v for (k,v) in d.items() if type(v) != int])

OUTPUT:

['one', 'two', 'three', 'four']
DirtyBit
  • 16,613
  • 4
  • 34
  • 55