Remove dictionary from list with multiple conditions - python

list1 = [
{'id': 1, 'country': 'Italy'},
{'id': 2, 'country': 'Spain'},
{'id': 3, 'country': 'Japan'}
]
I use this code to remove from list1 every dictionary that has country != Italy:
list2 = [element for element in list1 if element['country'] == 'Italy']
But I to include in list2 dictionaries which country == 'Italy' AND country == 'Spain' and remove all the others (or even better pop them from list1 without creating another one). How can I do this in one line=

If you really want a one-liner, you can use a list comprehension with an in-place list update:
list1[:] = [d for d in list1 if d['country'] in ('Spain', 'Italy')]

Related

Create many lists from list of dictionaries that have different structures

I have a big list of dictionaries. And the dictionaries don´t have the same structure. But, I don´t know all the structures (my list has 1 million elements).
For example:
mylist = [{'name': 'Juan Carlos','age':38},{'name':'David','country':'Brazil'},
{'name':'Agustina', 'country': 'Argentina'},{'name': 'Renzo','age':24}]
I want to separate mylist into different lists, and each list has dictionaries with the same keys.
For example:
list1 = [{'name': 'Juan Carlos','age':38},{'name': 'Renzo','age':24}]
list2 = [{'name':'David','country':'Brazil'},{'name':'Agustina', 'country': 'Argentina'}]
The problem is I don´t know how many sublists I'm going to have.
To do this, you need to create a dictionary where the key is the set of keys that are present:
mylist = [{'name': 'Juan Carlos','age':38},{'name':'David','country':'Brazil'},{'name':'Agustina', 'country': 'Argentina'},{'name': 'Renzo','age':24}]
sublists = {}
for sl in mylist:
keys = tuple(set(sl.keys()))
if keys not in sublists:
sublists[keys] = []
sublists[keys].append( sl )
print( sublists )
Output:
{('name', 'age'): [{'name': 'Juan Carlos', 'age': 38}, {'name': 'Renzo', 'age': 24}], ('name', 'country'): [{'name': 'David', 'country': 'Brazil'}, {'name': 'Agustina', 'country': 'Argentina'}]}
You can use a frozenset of keys as a new key:
mylist = [{'name': 'Juan Carlos','age':38},{'name':'David','country':'Brazil'},
{'name':'Agustina', 'country': 'Argentina'},{'name': 'Renzo','age':24}]
sep = {}
for d in mylist:
sep.setdefault(frozenset(d), []).append(d)
and then you can get a list of lists:
print(sep.values())

How to get dictionary value from key in a list?

I am trying to create a new list from a list of dictionary items.
Below is an example of 1 dictionary item.
{'id': 'bitcoin',
'symbol': 'btc',
'name': 'Bitcoin',
'current_price': 11907.43,
'market_cap': 220817187069,
'market_cap_rank': 1}
I want the list to just be of the id item. So what I am trying to achieve is a list with items {'bitcoin', 'etc', 'etc}
You can use list comprehension:
my_list = [{'id': 'bitcoin', 'symbol': 'btc', ...}, ...]
[d['id'] for d in my_list]
Which translates to : for each dictionary in my_list, extract the 'id' key.
id_list = [d["id"] for d in dictlist ]
This should work for you
list = [ i['id'] for i in list_of_dict]
this should help
Simple and readable code that solves the purpose:
main_list = []
for item in main_dict:
main_list.append(item.get("id", None))
print(main_list)

Making dictionary from two lists

I have two lists
l1 = ['cat','dog']
l2= [1,2]
Now I want to make a dictionary like this:
dict { {'name':cat,'id'=1}{'name':dog,'id'=2}}
I am using zip but that's not fulfilling my requirement.
result = [{'name': name, 'id': id} for (name, id) in zip(l1, l2)]
It doesn't make sense for the container all the individual dicts are in to be a dict as well (unless you want to key it on, say, id).
If you have a lot of keys and you don't want to create dict comprehension and declare what goes where.
l1 = ['cat','dog']
l2= [1,2]
[dict(zip(['name', 'id'], el)) for el in zip(l1,l2)]
Output:
[{'id': 1, 'name': 'cat'}, {'id': 2, 'name': 'dog'}]

Python - Return list of dictionaries with unique Key:Value pair

I have a long list of dictionaries that for the most part do not overlap. However, some of the dictionaries have the same 'Name' field and I'd only like unique names in the list of dictionaries. I'd like the first occurrence of the name to be the one that stays and any thereafter be deleted from the list.
I've put a short list below to illustrate the scenario:
myList = [
{'Name':'John', 'Age':'50', 'Height':'70'},
{'Name':'Kathy', 'Age':'43', 'Height':'65'},
{'Name':'John','Age':'46','Height':'68'},
{'Name':'John','Age':'50','Height':'72'}
]
I'd like this list to return the first 'John' and Kathy, but not the second or third Johns and their related information.
An acceptable, but not optimal solution would also be not having dictionaries with the same name next to each other.
You could run over the list and keep a set of unique names. Every time you encounter a new name (i.e., a name that isn't in the set), you add it to the set and the respective dict to the result:
def uniqueNames(dicts):
names = set()
result = []
for d in dicts:
if not d['Name'] in names:
names.add(d['Name'])
result.append(d)
return result
You can easily write a for-loop for this.
def getName(name):
'''Gets first occurence of name in list of dicts.'''
for i in myList:
if i['Name'] == name:
return i
Initial list:
my_list = [
{'Name':'John', 'Age':'50', 'Height':'70'},
{'Name':'Kathy', 'Age':'43', 'Height':'65'},
{'Name':'John','Age':'46','Height':'68'},
{'Name':'John','Age':'50','Height':'72'}
]
The logical (potentially newbie-friendlier) way:
names = set()
new_list = []
for d in my_list:
name = d['Name']
if name not in names:
new_list.append(d)
names.add(d['Name'])
print new_list # [{'Age': '50', 'Name': 'John', 'Height': '70'}, {'Age': '43', 'Name': 'Kathy', 'Height': '65'}]
A one-liner way:
new_list = {d['Name']: d for d in reversed(my_list)}.values()
print new_list # [{'Age': '43', 'Name': 'Kathy', 'Height': '65'}, {'Age': '50', 'Name': 'John', 'Height': '70'}]
Note: The one-liner will contain the first occurrence of each name, but it will return an arbitrarily ordered list.

Python: iterate through dictionary and create list with results

I would like to iterate through a dictionary in Python in the form of:
dictionary = {
'company': {
0: 'apple',
1: 'berry',
2: 'pear'
},
'country': {
0:'GB',
1:'US',
2:'US'
}
}
To grab for example:
every [company, country] if country is "US"
So I get a list in the form:
[["berry", "US"], ["pear", "US"]]
I suppose your keys are strings as well and the output is a list of lists, where the elements are strings, too. Then this problem can be solved via list comprehension.
The idea is to use list comprehension to fill the list of [company, country]-lists, but only if the country is 'US'. key represents the keys of the inner dictionaries (i.e 0, 1, 2).
dictionary = {'company': {0: 'apple', 1: 'berry', 2: 'pear'}, 'country': {0: 'GB', 1: 'US', 2:'US'}}
y = [[dictionary['company'][key], dictionary['country'][key]] for key in dictionary['country'] if dictionary['country'][key] == 'US']
It returns
[['berry', 'US'], ['pear', 'US']]
myList = []
list(map(lambda x: myList.append(x) if x[1]=='US' else None,
zip(dictionary['company'].values(), dictionary['country'].values())))

Categories