I have a list of dictionaries looking like this:
[{'customer': 'Charles', 'city': 'Paris'}, {'customer': 'John', 'city': 'New York'}, {'customer': 'Jean', 'city': 'Paris'}]
I tried something using collections which will return me the name of the most common city in this list of dictionaries:
city_counts = Counter(c['city'] for c in customers)
return city_counts .most_common(1)[0][0]
From this, I would like to return a list of all customers who are not in this city.
So, if I take the list I gave above, ['John'] should be the output.
I there a best way to do it ?
Related
Based on a list of fastfoods (list of dictionaries), for each fastfood (each dictionary), I'm trying to 1) extract the competitor's name and then 2) use that competitor's name to retrieve its shortname.
Currently my solution really doesn't make sense and I have a feeling it might be recursive? I'm really having an issue conceptualizing this.
fastfoods = [{'id': 30, 'name': 'McDonalds', 'shortname': 'MC', 'competitor': 'BurgerKing'}, {'id': 47, 'name': 'BurgerKing', 'shortname': 'BK', 'competitor': None}]
for fastfood in fastfoods:
competitor_name = fastfood.get('competitor')
short_name = fastfood.get('shortname')
for fastfood in fastfoods:
if competitor_name == short_name:
print(fastfood.get('shortname')
Here's a visualization of what I'm trying to achieve:
In this limited example I have (real example has thousands of dictionaries, but I'm using 2 just for the example.
So here, I loop over the dictionaries, I reach the first dictionary, I extract the competitor's name ('BurgerKing'). At this point, I want to search for 'BurgerKing' as a 'name' field (not as a competitor field). Once that's found, I access that dictionary where the 'name' field == 'BurgerKing' and extract the shortname ('BK').
I think you're looking for something like this:
byName = {dct['name']:dct for dct in fastfoods}
for fastfood in fastfoods:
if 'competitor' in fastfood and fastfood['competitor'] is not None:
competitor = byName[fastfood['competitor']]
if 'shortname' in competitor:
print(competitor['shortname'])
else:
print(f"competitor {fastfood['competitor']} has no shortname")
Explanation:
create byName, a dictionary that indexes dicts in fastfoods by their name entry
iterate over all dicts in fastfoods
if a given dict has a competitor entry and it's non-null, look up the dict for that competitor by name in byName and if it has a shortname entry print it
otherwise print a message indicating there is no shortname entry for the competitor (you can do something different in this case if you like).
I would first construct a dictionary that maps a name to its shortened version, and then use it. This would be way faster than looking for the competitor in the list over and over again.
fastfoods = [{'id': 30, 'name': 'McDonalds', 'shortname': 'MC', 'competitor': 'BurgerKing'}, {'id': 47, 'name': 'BurgerKing', 'shortname': 'BK', 'competitor': None}]
name_to_short = {dct['name']: dct['shortname'] for dct in fastfoods}
for dct in fastfoods:
print(f"The competitor of {dct['name']} is: {name_to_short.get(dct['competitor'], 'None')}")
# The competitor of McDonalds is: BK
# The competitor of BurgerKing is: None
i am trying to convert these nested tuples into a dictionary
country_list = [[('Finland', 'Helsinki')], [('Sweden', 'Stockholm')], [('Norway', 'Oslo')]]
and to add custom key values to such as the output would be
[{'country': 'FINLAND', 'city': 'HELSINKI'},
{'country': 'SWEDEN', 'city': 'STOCKHOLM'},
{'country': 'NORWAY', 'city': 'OSLO'}]
i've done this:
new_country=[list(country) for sublist in
country_list for country in sublist]
print(new_country)
which obviously returns a list, i have tried using the dict() function but it throws an error, and i am not sure how to add these custom key values
Try:
[{'country':i[0][0],'city':i[0][1]} for i in country_list]
output:
[{'country': 'Finland', 'city': 'Helsinki'},
{'country': 'Sweden', 'city': 'Stockholm'},
{'country': 'Norway', 'city': 'Oslo'}]
To be clear this returns a list of dictionaries, not a dictionary. This does match the desired output though.
I am not sure how to ask this as I'm not sure if I'm using the proper key words. I have a dictionaries in a variable x. I unpack (is that the right term?) to a object of type Org like so:
org = Org(**x)
where x is of the form:
{'user': 'joe#example.com', 'sk': 'meta_3', 'location': 'Dubai', 'name': 'Thomas'}
This works so far. I get an object org of type Org.
But my Q is: how do I handle if x is a list of dicts i.e. x is
[
{'user': 'joe#example.com', 'sk': 'meta_3', 'location': 'Dubai', 'name': 'Thomas'},
{'user': 'sam#example.com', 'sk': 'meta_4', 'location': 'Spain', 'name': 'Sam'}
]
How do I unpack that to a list of Org objects?
If x_list is your list containing dicts:
org_list = []
for x in x_list:
org = Org(**x)
org_list.append(org)
Now you have a list org_list that contains all created Org objects.
I have a very big dictionary with keys containing a list of items, these are unordered. I would like to group certain elements in a new key. For example
input= [{'name':'emp1','state':'TX','areacode':'001','mobile':123},{'name':'emp1','state':'TX','areacode':'002','mobile':234},{'name':'emp1','state':'TX','areacode':'003','mobile':345},{'name':'emp2','state':'TX','areacode':None,'mobile':None},]
for above input i would like to group areacode and mobile in a new key contactoptions
opdata = [{'name':'emp1','state':'TX','contactoptions':[{'areacode':'001','mobile':123},{'areacode':'002','mobile':234},{'areacode':'003','mobile':345}]},{'name':'emp2','state':'TX','contactoptions':[{'areacode':None,'mobile':None}]}]
i am doing this now with a two long iterations. i wanted to achieve the same more efficiently as the number of records are large. open to using existing methods if available in packages like pandas.
Try
result = (
df.groupby(['name', 'state'])
.apply(lambda x: x[['areacode', 'mobile']].to_dict(orient='records'))
.reset_index(name='contactoptions')
).to_dict(orient='records')
With regular dictionaries, you can do it in a single pass/loop using the setdefault method and no sorting:
data = [{'name':'emp1','state':'TX','areacode':'001','mobile':123},{'name':'emp1','state':'TX','areacode':'002','mobile':234},{'name':'emp1','state':'TX','areacode':'003','mobile':345},{'name':'emp2','state':'TX','areacode':None,'mobile':None}]
merged = dict()
for d in data:
od = merged.setdefault(d["name"],{k:d[k] for k in ("name","state")})
od.setdefault("contactoptions",[]).append({k:d[k] for k in ("areacode","mobile")})
merged = list(merged.values())
output:
print(merged)
# [{'name': 'emp1', 'state': 'TX', 'contactoptions': [{'areacode': '001', 'mobile': 123}, {'areacode': '002', 'mobile': 234}, {'areacode': '003', 'mobile': 345}]}, {'name': 'emp2', 'state': 'TX', 'contactoptions': [{'areacode': None, 'mobile': None}]}]
As you asked, you want to group the input items by 'name' and 'state' together.
My suggestion is, you can make a dictionary which keys will be 'name' plus 'state' such as 'emp1-TX' and values will be list of 'areacode' and 'mobile' such as [{'areacode':'001','mobile':123}]. In this case, the output can be achieved in one iteration.
Output:
{'emp1-TX': [{'areacode':'001','mobile':123}, {'areacode':'001','mobile':123}, {'areacode':'003','mobile':345}], 'emp2-TX': [{'areacode':None,'mobile':None}]}
'data' is a list made-up of dictionaries. enter code hereI want to count the number of 'City' present in 'data' list without using a loop.
data = [{'City': 'Solta', 'Country': 'Croatia'},
{'City': 'Greenville', 'Country': 'USA'},
{'City': 'Buenos Aires', 'Country': 'Argentina'},
{'City': 'Los Cabos', 'Country': 'Mexico'}]
'''
#This code is working
count = 0
for i in range(len(data)):
if('City' in data[i].keys()):
count = count+1
print('No of Cities: ',count)
'''
I want to know, Is there any other way to calculate no. of cities in it, without using a loop??
it's easy.use this:
len(data)
it will give you length of list.