This question already has answers here:
How do I sort a dictionary by key?
(32 answers)
Apply function to each element of a list
(4 answers)
Closed 5 months ago.
I have a list of dictionaries where the order of the keys is not consistent. Ideally I would like 'vid' to always come first with 'name' being second. As you can see below, sometimes 'name' comes first. How can I sort this list of dictionaries to always have 'vid' first?
viri_assets = [
{'vid': 'transpower_036', 'name': '221_02_PB_520_REF_174050'},
{'name': '242_07_DINA_HSTLR_YT_210238', 'vid': 'transpower_168'},
{'vid': 'transpower_170', 'name': '242_08_DINA_HSTLR_YT_210220'},
{'name': '251_PS04_PB_520_REF_109968', 'vid': 'transpower_166'},
{'vid': 'transpower_165', 'name': '251_PS05_PB_520_REF_109967'},
{'name': '31089', 'vid': 'transpower_064'}]
I have tried using sorted(viri_assets, key=lambda d: list(d.keys())) but it does not work.
You don't want to call sorted on your list, but on each dict of the list
Use .items() to get key-value pairs for each dict, and it'll sort them by the first element of the pair: the key. Set reverse to True to get "vid" before "name".
viri_assets = [{'vid': 'transpower_036', 'name': '221_02_PB_520_REF_174050'},
{'vid': 'transpower_065', 'name': '222_05_KAL_T2E_YT_344991'},
{'name': '226_02_INTL_PRSTR_ET_499802', 'vid': 'transpower_156'}]
viri_assets = [dict(sorted(d.items(), reverse=True)) for d in viri_assets]
print(viri_assets)
Output:
[{'vid': 'transpower_036', 'name': '221_02_PB_520_REF_174050'},
{'vid': 'transpower_065', 'name': '222_05_KAL_T2E_YT_344991'},
{'vid': 'transpower_156', 'name': '226_02_INTL_PRSTR_ET_499802'}]
Related
I have list (of dictionary) and dictionary in Python as below
List1= [ { 'Id': 'i-0f76fasa','Port': 80,'State': 'unavailable','TargetGrnArn' :'ABC123'}
{ 'Id': 'i-0f97wewr','Port': 88,'State': 'unavailable','TargetGrnArn' :'ABC123'}
{ 'Id': 'i-0f12xrde','Port': 90,'State': 'unavailable','TargetGrnArn' :'XYZ234'}
{ 'Id': 'i-0f26fade','Port': 90,'State': 'unavailable','TargetGrnArn' :'XYZ234'}]
Dict1={"TargetGroupName":1245,"TargetGroupArn": ABC123,"HealthCheckProtocol":TCP,"HealthCheckPort":22,"HealthCheckEnabled":YES,"HealthCheckIntervalSeconds":20,"HealthCheckTimeoutSeconds":60,"HealthyThresholdCount":3,"HealthCheckPath":/tmp}
The requirement is TargetGrnArn is matched with List new list or dictionary should have 2 items with same values as in Dict1 in addition to values in List1.
final output requirement is
{"TargetGroupName":1245,"TargetGroupArn": ABC123,"HealthCheckProtocol":TCP,"HealthCheckPort":22,"HealthCheckEnabled":YES,"HealthCheckIntervalSeconds":20,"HealthCheckTimeoutSeconds":60,"HealthyThresholdCount":3,"HealthCheckPath":/tmp ,'Id': 'i-0f76fasa','Port': 80,'State': 'unavailable'}
{"TargetGroupName":1245,"TargetGroupArn": ABC123,"HealthCheckProtocol":TCP,"HealthCheckPort":22,"HealthCheckEnabled":YES,"HealthCheckIntervalSeconds":20,"HealthCheckTimeoutSeconds":60,"HealthyThresholdCount":3,"HealthCheckPath":/tmp , 'Id': 'i-0f97wewr','Port': 88,'State': 'unavailable'}
Here Information in Dict1 will remain same in both the items but rest information from list will be different.
This question already has answers here:
Change the name of a key in dictionary
(23 answers)
Closed 1 year ago.
I would like to know what is the most elegant or pythonic way to copy specific values from one dictionary into another, only if the values are not None, empty, or empty dict.
The new dictionary will have different key names than the original one.
For example, let's assume I got a response from API and I converted json to dict
customer = [{
'name': 'John',
'email': 'johnsmith#gmail.com',
'phoneNumber': '9999999',
'country': 'USA',
'city': None,
'preferences': {}
}]
new_customer_dict = {}
for client in customer:
if client.get('name'):
new_customer_dict ['customer_name'] = client['name']
if client.get('email'):
new_customer_dict['customer_email'] = client['email']
How about something like this:
>>> customer_keys = [k for client in customer for k in client.keys()]
>>> customer_keys
['city', 'name', 'phoneNumber', 'email', 'country', 'preferences']
>>> new_customer_dict = {'customer_{}'.format(k): client.get(k)
... for client in customer
... for k in customer_keys
... if client.get(k) is not None
... and client.get(k)}
>>> new_customer_dict
{'customer_name': 'John', 'customer_phoneNumber': '9999999', 'customer_country': 'USA', 'customer_email': 'johnsmith#gmail.com'}
Basically, first, you make a list of all the keys you want to look for. Next, you iterate over the list while making sure that value (of dict) is not None. You also check if the value (of dict) is not None.
Hope you got the idea!
I have a nested dictionary (category and subcategories), dict, that I am having trouble sorting.
The output of dict is:
{u'sports': {u'basketball': {'name': u'Basketball', 'slug': u'basketball'}, u'baseball': {'name': u'Baseball', 'slug': u'baseball'}}, u'dance': {u'salsa': {'name': u'Salsa', 'slug': u'salsa'}}, u'arts': {u'other-5': {'name': u'Other', 'slug': u'other-5'}, u'painting': {'name': u'Painting', 'slug': u'painting'}}, u'music': {u'cello': {'name': u'Cello', 'slug': u'cello'}, u'accordion': {'name': u'Accordion', 'slug': u'accordion'}}}
How can I sort this dictionary so that the 'other' subcategory always shows up at the end of the nested dictionary. For example the order for the "arts" category should be:
..., u'arts': {u'painting': {'name': u'Painting', 'slug': u'painting'}, u'other-5': {'name': u'Other', 'slug': u'other-5'}}...
You have some major concept misunderstanding about dictionary. Dictionary in python is like a hash table, hash table has no order. The output of the dict is really environment dependent so you couldn't depend on that. You might see one way of the output while other people see another way. You should consider using OrderedDict instead.
Python dictionaries (regular dict instances) are not sorted. If you want to sort your dict, you could:
from collections import OrderedDict
mynewdict = OrderedDict(sorted(yourdict.items()))
An OrderedDict does not provide a sorting mechanism, but only respect the order of the keys being inserted on it (we sort those keys calling sorted beforehand).
Since you need a specific criteria (lets say your keys are alphabetically ordered except for the "other" key which goes to the end), you need to declare it:
def mycustomsort(key):
return (0 if key != 'other' else 1, key)
mynewdict = OrderedDict(sorted(yourdict.items(), key=mycustomsort))
This way you are creating a tuple for the nested criteria: the first criteria is other vs. no-other, and so the 0 or 1 (since 1 is greater, other comes later), while the second criteria is the key itself. You can remove the second criteria and not return a tuple if you want, but only the 0 and 1, and the code will work without alphabetical sort.
This solution will not work if you plan to edit the dictionary later, and there is no standard class supporting that.
This question already has an answer here:
Get a list of values from a list of dictionaries?
(1 answer)
Closed 8 years ago.
So I am bit new to Python. I am dealing with a problem I want to call the key ['name'] and get the following result:
['Tom', 'Mark' 'Pam']
However i seem to be in a little trouble due to multiple dictionaries in a list as seen in the code bellow.
people = [
{'name': "Tom", 'age': 10},
{'name': "Mark", 'age': 5},
{'name': "Pam", 'age': 7}
]
Thanks in advance!
You can use a list comprehension :
>>> [i['name'] for i in people if 'name' in i]
['Tom', 'Mark', 'Pam']
I'm trying to sort this dict based on the key "order". Kindly, find below sample dict :-
{'about-us': [{'name': 'CONSTITUTION', 'order': u'2', 'uri': 'constitution'},
{'name': 'EXECUTIVE COMMITTEE',
'order': u'3',
'uri': 'executive-committee'},
{'name': 'FINANCIAL INFO',
'order': u'4',
'uri': 'financial-info'},
{'name': 'SPONSORS AND AFFILIATIONS',
'order': u'5',
'uri': 'sponsors-and-affiliations'},
{'name': 'ABOUT', 'order': u'1', 'uri': 'about'}]}
Tried using this code, but I got an error
sorted(sub_links, key=lambda x: sub_links[x]['order'])
TypeError: list indices must be integers, not str
Any hint?
You can't sort the dictionary itself. Dictionary in python does not have an order.
Trying to sort dictionary will pass keys of the dictionary to the key function. sub_links[x] => sub_links['about-us']; sub_links[x]['order'] fails because sub_links[x] returns a list.
You can sort the list inside the dictionary: d['about-us']
Also the usage of the sorted function should be changed: sorted passes each item to the key function, not the index of the item.
>>> sorted(d['about-us'], key=lambda x: int(x['order']))
[{'uri': 'about', 'name': 'ABOUT', 'order': u'1'},
{'uri': 'constitution', 'name': 'CONSTITUTION', 'order': u'2'},
{'uri': 'executive-committee', 'name': 'EXECUTIVE COMMITTEE', 'order': u'3'},
{'uri': 'financial-info', 'name': 'FINANCIAL INFO', 'order': u'4'},
{'uri': 'sponsors-and-affiliations', 'name': 'SPONSORS AND AFFILIATIONS', 'order': u'5'}]
If you need to sort all the dictionary values in place, loop over the values.
for value in d.values(): # use `itervalues` In Python 2.x
value.sort(key=lambda x: int(x['order']))
falsetru showed what you probably meant to do, but here's an explanation of the error you are seeing:
The key lambda function receives the dictionary's keys as its argument x when called--in this case, the call looks something like this when performed on the one and only key in the dictionary:
# this is JUST for demonstrating the execution of the code--this is not actual Python code
lambda("about-us"):
return sub_links["about-us"]["order"]
When this executes, sub_links["about-us"] returns the value of that key, which is a list. When the next part of the statement executes (<the list that got returned>["order"]), the TypeError gets thrown because lists require integer indices.
There's a bigger problem here--it seems you called sorted on the whole dictionary, which only contains 1 value. It doesn't make sense to sort something with only 1 entry, and it should not be used to sort what you seem to want to sort, which is the inner list of dictionaries.
If you want to sort the inner list of dictionaries (the corresponding dict value for the "about-us" key), you'll need something like this (as falsetru also suggested):
sorted(sub_links["about-us"], key=lambda d: int(d["order"]))