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']
Related
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'}]
My question is an extension to this:
Python Accessing Values in A List of Dictionaries
I want to only return values from dictionaries if another given value exists in that dictionary.
In the case of the example given in the linked question, say I only want to return 'Name' values if the 'Age' value in the dictionary is '17'.
This should output
'Suzy'
only.
result = [d["Name"] for d in dicts if d.get("Age") == 17)]
Of course this would select all nanes that satisfy the condition. You can put that in a function.
In the following case :
listname= [
{'Name': 'Albert' , 'Age': 16},
{'Name': 'Suzy', 'Age': 17},
{'Name': 'Johnny', 'Age': 13}
]
If you want return only people Name when "age == 17" use :
for d in listname:
if d['Age'] == 17 :
print (d['Name'])
Use a condition inside your for.
Edit 10/01/2022 : Change "list" to "listname", cause list il already reserved in python.
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!
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I am creating a dictionary for a JSON file, through the use of a for loop.
However my for loop overwrites the entries
second_dict={}
third_dict={}
name=['suzen','lilly','sara']
hobbies=['chess','reading','dancing']
age=[13,14,15]
for i in range(len(name)):
second_dict["hobbies"]=hobbies[i]
second_dict["age"]=age[i]
third_dict[name[i]]=second_dict
print(third_dict)
I am getting this output
{'suzen': {'hobbies': 'chess', 'age': 13},
'lilly': {'hobbies': 'chess', 'age': 13},
'sara': {'hobbies': 'chess', 'age': 13}}
Instead of getting this one
{'suzen': {'hobbies': 'chess', 'age': 13},
'lilly': {'hobbies': 'reading', 'age': 14},
'sara': {'hobbies': 'dancing', 'age': 15}}
can anyone please point out my mistake?
thank you
new_dict={}
name=['suzen','lilly','sara']
hobbies=['chess','reading','dancing']
age=[13,14,15]
x = zip(name, hobbies, age)
for n,h,a in x:
new_dict[n]={'hobbies': h, 'age': a}
print(new_dict)
third_dict={}
name=['suzen','lilly','sara']
hobbies=['chess','reading','dancing']
age=[13,14,15]
for i in range(len(name)):
second_dict={}
second_dict["hobbies"]=hobbies[i]
second_dict["age"]=age[i]
third_dict[name[i]]=second_dict
print(third_dict)
As pointed in comments, you should create a new object for each second_dict, there are 3 second_dict.
This question already has answers here:
Creating a list of dictionaries results in a list of copies of the same dictionary
(4 answers)
Closed 1 year ago.
I wanted to create a list that contains x amount of dictionaries all containing the same keys but with different values that's made in a for loop:
Something like
[{'name': Brenda, 'Age': 22, 'Sex': Female},
{'name': Jorda, 'Age': 32, 'Sex': Male},
{'name': Richard, 'Age': 54, 'Sex': Male}]
My code is this:
people = []
person = {}
humans = gethumans()
for human in humans:
number_people, people_data = People.data()
person['name'] = human.name
person['age'] = human.age
person['Sex'] = human.name
people.append(person)
My output is something like this:
[{'name': Richard, 'Age': 54, 'Sex': Male},
{'name': Richard, 'Age': 54, 'Sex': Male}
{'name': Richard, 'Age': 54, 'Sex': Male}]
Since the dictionary values are getting replaced and not added and it's just appending the same dictionary. How can I get around this?
When you append the dictionary person to the list people you are just appending a reference to the dictionary to the list, so the list ends up containing just references to the SAME dictionary.
Since each time through the loop you overwrite the dictionary with new values, at the end the list contains just references to the last person you appended.
What you need to do is create a new dictionary for every person, for example:
for human in humans:
number_people, people_data = People.data()
person = dict()
person['name'] = human.name
person['age'] = human.age
person['Sex'] = human.name
people.append(person)
You each time edit the same dictionary, so you do not construct a new one, but edit the old one. Since you each time append the same dictionary to the list, in the end the list contains the same dictionary n times, and all edits are processed on that dictionary.
You thus have to construct a new dictionary in each iteration in the for loop:
people = []
humans = gethumans()
for human in humans:
number_people, people_data = People.data()
person = {
'name': human.name,
'age': human.age,
'sex': human.sex
}
people.append(person)
I here replaced 'Sex' with 'sex' (since it is strange to have inconsistent key names), and used human.sex instead of human.name.
Here people.data() do not seem to do anything, you can thus use list comprehension here to generate the list:
people = [
{ 'name': human.name, 'age': human.age, 'sex': human.sex }
for human in humans
]
This will construct a list with all the dictionaries. Given the for loop had no side-effects (this looks to be the case), the above will work.