Lets say I have a list
demo = [['Adam', 'Chicago', 'Male', 'Bears'], ['Brandon', 'Miami', 'Male', 'Dolphins']]
I want to make a list of dictionaries using a comprehension that looks like
[{'Adam':'Chicago', 'Gender':'Male', 'Location':'Chicago', 'Team':'Bears'},
{'Brandon':'Miami', 'Gender':'Male', 'Location':'Miami', 'Team':'Dolphins'} }
It easy enough to assign two starting values to get something like
{ s[0]:s[1] for s in demo}
but is there a legitimate way to assign multiple values in this comprehension that may look like
{ s[0]:s[1],'Gender':s[2], 'Team':s[3] for s in demo}
Its such a specific question and the I dont know the terms for searching so Im having a hard time finding it and the above example is giving me a syntax error.
Dictionary comprehensions build single dictionaries, not lists of dictionaries. You say you want to make a list of dictionaries, so use a list comprehension to do that.
modified_demo = [{s[0]:s[1],'Gender':s[2], 'Team':s[3]} for s in demo]
You can use zip to turn each entry into a list of key-value pairs:
dicts= [dict(zip(('Name','Gender','Location', 'Team'), data) for data in demo]
You don't want a 'Name' label, you want to use the name as a label which duplicates location. So, now you need to fix up the dicts:
for d in dicts:
d[d['Name']] = d['Location']
del d['Name'] # or not, if you can tolerate the extra key
Alternatively, you can do this in one step:
dicts = [{name:location,'Location':location,'Gender':gender, 'Team':team} for name,location,gender,team in demo]
Your requirement just looks odd, are you sure you aren't trying to logically name the fields (which makes far more sense):
>>> demo = [['Adam', 'Chicago', 'Male', 'Bears'], ['Brandon', 'Miami', 'Male', 'Dolphins']]
>>> [dict(zip(['name', 'location', 'gender', 'team'], el)) for el in demo]
[{'gender': 'Male', 'team': 'Bears', 'name': 'Adam', 'location': 'Chicago'}, {'gender': 'Male', 'team': 'Dolphins', 'name': 'Brandon', 'location': 'Miami'}]
Related
me={'name': 'adeen', 'passion': ['reading','gardening']}
How could I change 'reading' in it or if I have placed a variable in it?
You can change values (Nested lists) by their index and dictionary key.
If you want change 'reading' value, you can do it:
me
{'name': 'adeen', 'passion': ['reading', 'gardening']}
me['passion']
['reading', 'gardening']
me['passion'][0] = 'Hello'
me
{'name': 'adeen', 'passion': ['Hello', 'gardening']}
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.
I'm very new to programming and Python and trying to figure things out. I'm trying to take items out of a list and append the keys and values to a dictionary but I can't figure out how. I tried using the dictionary's Update method but I'm only getting the last item from my list, not all the items. Here is my code:
a = {}
names = [ {'name': 'Bart'}, {'name': 'Lisa'}, {'name': 'Maggie'} ]
for name in names:
a.update(name)
The result I'm getting back is:
{'name': 'Maggie'}
But I want this in my new dictionary:
{'name': 'Bart'}, {'name': 'Lisa'}, {'name': 'Maggie'}
I wanted to put the items from the list inside the dictionary in order to access the values. I need all of the names but maybe there is a much easier way to do it.
Any hints would be great. Thanks.
With same key value you cant update a dict from list of dict. You can get a dict with key a list of values.
{'name': ['Bart', 'Lisa', 'Maggie']}
a={}
for n in names:
... for k in n:
... for k,v in [(k,n[k])]:
... if k not in a:a[k]=[v]
... else: a[k].append(v)
I have a dictionary with a key and a pair of values, the values are stored in a List. But i'm keeping the list empty so i can .append its values ,i cant seem to be able to do this
>>>myDict = {'Numbers':[]}
>>>myDict['Numbers'[1].append(user_inputs)
doesn't seem to work, returns an error . How do i refer to the list in myDict so i can append its values.
Also is it possible to have a dictionary inside a list and also have another list inside? if so? what is its syntax or can you recommend anyother way i can do this
>>>myDict2 = {'Names': [{'first name':[],'Second name':[]}]}
do i change the second nested list to a tuple?? Please lets keep it to PYTHON 2.7
You get an error because your syntax is wrong. The following appends to the list value for the 'Numbers' key:
myDict['Numbers'].append(user_inputs)
You can nest Python objects arbitrarily; your myDict2 syntax is entirely correct. Only the keys need to be immutable (so a tuple vs. a list), but your keys are all strings:
>>> myDict2 = {'Names': [{'first name':[],'Second name':[]}]}
>>> myDict2['Names']
[{'first name': [], 'Second name': []}]
>>> myDict2['Names'][0]
{'first name': [], 'Second name': []}
>>> myDict2['Names'][0]['first name']
[]
You should access the list with myDict['Numbers']:
>>>myDict['Numbers'].append(user_inputs)
You can have dicts inside of a list.
The only catch is that dictionary keys have to be immutable, so you can't have dicts or lists as keys.
You may want to look into the json library, which supports a mix of nested dictionaries and lists.
In addition, you may also be interested in the setdefault method of the dictionary class.
Format is something like:
new_dict = dict()
some_list = ['1', '2', '3', ...]
for idx, val in enumerate(some_list):
something = get_something(idx)
new_dict.setdefault(val, []).append(something)
Sorry, I couldn't think of a better title for my question.
So I'm a starter at Python and I really trying to learn how to use it. My current problem deals with creating a simple way to reduce the results received from a python query.
If I understand what I'm dealing with, the LDAP query returns a List of a List of Dictionary where value in the Dictionary is a List. That's a lotta stuff there to traverse through so I figured there has to be a nice magical python way to convert this to a List of a Dictionary where the value of the Dictionary is just a simple string.
Currently, my code just simply to get the List of Dictionary but I still have the Dictionary values as a List themselves
for item in data:
results.append(item[1])
Once again, I'm a beginner so I don't really understand what to do from there. I'm also using Django if that's gonna help anyone understand my plight.
Edit (added data example):
The Structure is kinda like this:
data[index][1] = {'uid': ['restest'], 'mail': [''], 'givenName': ['Research'], 'cn': ['Research Test Account'], 'sn': ['Account']}
I'd like it to be instead of 'givenName': ['Research'] to be 'givenName': 'Reaseach'
Haha I'm not sure you ever want such a complicated data structure around. Consider refactoring your code to make your data structures easier to understand. Read: object-oriented programming, classes, functional programming principles.
Here's the answer if you just want to do it for a single dictionary:
data = {k:v[0] for (k,v) in data.items()}
Here it is in action:
>>> data = {'uid': ['restest'], 'mail': [''], 'givenName': ['Research'], 'cn': ['Research Test Account'], 'sn': ['Account']}
>>> data
{'mail': [''], 'sn': ['Account'], 'givenName': ['Research'], 'uid': ['restest'], 'cn': ['Research Test Account']}
>>> data = {k:v[0] for (k,v) in data.items()}
>>> data
{'mail': '', 'givenName': 'Research', 'cn': 'Research Test Account', 'sn': 'Account', 'uid': 'restest'}
All you're doing is re-mapping your dictionary to the first item of each list. If you want to iterate through all the levels of your structure and do this, just nest the above inside some list comprehensions:
[[[{k:v[0] for (k,v) in change_dict.items()} for change_dict in list_of_dicts]
for list_of_dicts in list_of_lists]
for list_of_lists in mydata]
It's not so bad to nest so many list comprehensions when you're only doing something to a "leaf" element in your data, but this is gonna get really messy if you try to manipulate your data structures at every level. See my comment at the beginning.