Join lists with dictionaries for given interval

Viewed 93

I have the following - maybe very simple - question.

I have a dictionary with several keys and values. For my relevant key, i have 10 entries, but i only need the entries 3-6 to be part of my string (simplified, in reality i have 1000 entries).

So far my code is this, but it plots me all 10 keys. I would like to make the program slice the list and print only elements 3-6 from mykey.

mydict = {"key1": "red",
          "key2": "grass",
          "key3": 2020,
          "mykey": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]}

string = ", ".join(f'{q:}' for q in mydict["mykey"]) + "\n"
1 Answers

To slice a list in python use the [] operator.


For example:

l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(l[1:6:2])

This code will print all the 2nd elements between 1 to 6 (exclude), so the output is:

[2, 4, 6]

The [] operator works in this way [start : stop : step] where start, stop, and step are integers.

In your code you can write this:

mydict = {"key2": "grass",
          "key3": 2020,
          "mykey": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]
         }

string = ", ".join(str(q) for q in mydict["mykey"][3:7]) + "\n"

# or in a simple way
string = ", ".join(mydict["mykey"][3:7]) + "\n"
Related