last day (15 days later) » 

11:33 PM
2
A: How to delete keys from multiple dictionaries in a list python

ettananyIn fact list does not have keys, list has indices, and dictionary has keys. In your case, you have a list of dictionaries, and what you need is to remove some keys (2 exactly: description and tournament_url) form each item (dictionary) of your list: for item in my_list: # my_list if the list th...

 
Wait, so I have a list of dictionaries? Damn, thanks a lot. I have been stuck on this shit forever.
 
@rassar this answers your question stackoverflow.com/a/5713303/4575071
 
@ettanany is there also a way to not remove it from the current list, but select which keys i want to keep, eg: i have a list with dictionaries that contain a variable amount of keys. del item wont do the trick here (or if you could perheps invert it. Can you help me out?
 
@Adam take a look at my edited answer, I added what you are looking for.
 
Im so thankful for your answer. Do the keys of keys_to_keep stay in that order? Or does it keep changing its position everytime i rerun the code?
 
11:33 PM
keys_to_keep is just a list of keys that you want to retrieve, the order is not important.
Do not forget to upvote and accept my answer :)
 
Uhm, i meant the order of keys in res ofcourse, my bad.
Hi there!
 
They may not always be in the same order, but I do not think you will need that
 
Well im asking because i noticed the order of my lists keep changing
Im busy with a small project that envolves a lot of nested lists and dicts
The thing is i got the following object
{a: 1, b: 2, c: [{xy: 99, wq: 78}, {xy: 99, wq: 78}, {xy: 99, wq: 78}]}
And I noticed python likes to mess up the order of lists/dicts
the sample is the row I get returned from an api
 
list is ordered, if you have [1, 2, 3] the order will never change
 
but I can only summon 1 line at a time through it
 
11:36 PM
but it is not the same for dictionary
 
Awh damn
so in order to create it into a huge CSV file, i just need to sort the dictionaries every time right?
 
you may need to read about OrderedDict, docs.python.org/2/library/…
is an ordered version of normal dictionary
 
Isn't simply sorting a normal dict alphabetically a easier way to achieve the result im looking for?
 
OrderedDict does not sort items alphabetically
but in the order they are added
 
11:54 PM
Okey so i was tinkering
and even after sorting them, python just adds the keys in a random position into a dictionary
 
yes, because that's a normal dictionary, you can sort them and add them to an ordered dictionay if you want to keep the order
it is too late here, I should leave
Good luck!
 
x = {'c': 3, 'b': 2, 'a': 1}
y = {}
for key, value in sorted(x.items()):
y.update({key:value})
print(y)
Okey thanks for all your help man! really appreciate it
Have a good night
 
You're welcome :)
 

last day (15 days later) »