How to get all unique IDs from the list of dicts?
Say you have a list of dicts like this {'id': 1, 'other_value':5}
So maybe;
items = [{'id': 1,开发者_JS百科 'other_value':5}, {'id': 1, 'other_value2':6}, {'id': 2, 'other_value':4}, {'id': 2, 'other_value2':3}]
Now, you can assume this is a small subset of the data. There are maybe thousands. Also the structure isn't specified by me, its given to me.
If I just want to get the IDs out I could do something like this:
ids = [i[id] for i in items]
However, you'll notice there are duplicate id's in the original data. so the question is; how can you tidily get the unique ID's?
I was hoping for something like:
ids = [i[id] for i in items if not in LIST]
but as far as i know there isn't a way to access the list in the generator.
of course I can do a for loop and easily do it that way. I was just curious to know if there was a more concise way of doing this.
if you want unique id's you can use a set:
set(i['id'] for i in items)
set(i['id'] for i in items)
but you might consider another data structure altogether, for example dict of lists:
items = {1: [5, 6], 2: [2, 4]}
精彩评论