0

Below is the dictionary set I have

dict = {'city':[('hyderabad','pune','chennai'),'state':[('Telangana','mumbai','tamilnadu')]}

I'm trying to remove the first two strings from the list in key value pair from this dictionary, so it will look the same as below

dict = {'city':[('chennai'),'state':[('tamilnadu')]}

I have tried:

for v in dict.values():
    del v[0:1]

but this deletes the whole list instead of first two indexes, need help in deleting only the first two indexes of each value list in key value pair

2
  • 1
    Please refrain from using pandas for trivial data structure manipulations like these. Commented Jun 22, 2021 at 18:21
  • This is not related to pandas, removing the tag Commented Jun 22, 2021 at 18:23

2 Answers 2

3

You can use list slicing:

dct = {
    "city": [("hyderabad", "pune", "chennai")],
    "state": [("Telangana", "mumbai", "tamilnadu")],
}

dct = {k: [l[2:] for l in v] for k, v in dct.items()}
print(dct)

Prints:

{
 'city': [('chennai',)], 
 'state': [('tamilnadu',)]
}
Sign up to request clarification or add additional context in comments.

Comments

3

Try this:

dictionary = {
   'city':[('hyderabad','pune','chennai')],
   'state':[('Telangana','mumbai','tamilnadu')]
}
dict_new = {}
for key, value in dictionary.items():
  dict_new[key] = [value[0][2:],]

print(dict_new)

Or, if you prefer to use comprehension notation...

dict_new = {key: [value[0][2:],] for key, value in dictionary.items()}
print(dict_new)

Output:

{
   'city': [('chennai',)], 
   'state': [('tamilnadu',)]
}

Btw.. Try don't use reserved words like dict, tuple, str, etc. like variables names

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.