I want to convert a list to a dictionary:
products=[['1','product 1'],['2','product 2']]
arr=[]
vals={}
for product in products:
vals['id']=product[0]
vals['name']=product
arr.append(vals)
print str(arr)
The result is
[{'id': '2', 'name': 'product 2'}, {'id': '2', 'name': 'product 2'}]
But I want something thing like that:
[{'id': '1', 'name': 'product 1'}, {'id': '2', 'name': 'product 2'}]
What you need to do is create a new dictionary for each iteration of the loop.
products=[['1','product 1'],['2','product 2']]
arr=[]
for product in products:
vals = {}
vals['id']=product[0]
vals['name']=product[1]
arr.append(vals)
print str(arr)
When you append an object like a dictionary to an array, Python does not make a copy before it appends. It will append that exact object to the array. So if you add dict1 to an array, then change dict1, then the array's contents will also change. For that reason, you should be making a new dictionary each time, as above.
For simplicity sake you could also make this into a one liner:
products=[['1','product 1'],['2','product 2']]
arr= [{"id":item[0], "name":item[1]} for item in products]
Which yields:
[{'id': '1', 'name': 'product 1'}, {'id': '2', 'name': 'product 2'}]
products=[['1','product 1'],['2','product 2']]
arr=[{'id':a[0], 'name': a[1]} for a in products]
print str(arr)
Would also work
products=[['1','product 1'],['2','product 2']]
arr=[]
for product in products:
vals = {}
for i, n in enumerate(['id', 'name', ....]): # to make it more dynamic?
vals[n]=product[i]
arr.append(vals)
or just use [0], [1] like stated in previous post
Related
I have this list of dicts:
[{'name': 'aly', 'age': '104'},
{'name': 'Not A name', 'age': '99'}]
I want the name value to be the key and the age value to be the value of new dict.
Expected output:
['aly' : '104', 'Not A name': '99']
If you want output to be single dict, you can use dict comprehension:
output = {p["name"]: p["age"] for p in persons}
>>> {'aly': '104', 'Not A name': '99'}
If you want output to be list of dicts, you can use list comprehension:
output = [{p["name"]: p["age"]} for p in persons]
>>> [{'aly': '104'}, {'Not A name': '99'}]
You can initialize the new dict, iterate through the list and add to the new dict:
lst = [{'name': 'aly', 'age': '104'}, {'name': 'Not A name', 'age': '99'}]
newdict = {}
for item in lst:
newdict[item['name']] = item['age']
This will help you:
d = [
{'name': 'aly', 'age': '104'},
{'name': 'Not A name', 'age': '99'}
]
dict([i.values() for i in d])
# Result
{'aly': '104', 'Not A name': '99'}
# In case if you want a list of dictionary, use this
[dict([i.values() for i in d])]
# Result
[{'aly': '104', 'Not A name': '99'}]
Just a side note:
Your expected answer looks like a list (because of [ ]) but values inside the list are dictionary (key:value) which is invalid.
Here is the easiest way to convert the new list of dicts
res = list(map(lambda data: {data['name']: data['age']}, d))
print(res)
I have a list of strings which contains spanish-recipesĀ“s ingredients and its quantities and I would like to get a list of dictionaries splitting every ingredient, unit and quantity.
This is the list:
ingredients=[
'50',
'ccs',
'aceite',
'1',
'hoja',
'laurel',
'\n',
'1',
'cabeza',
'ajos',
'1',
'vaso',
'vino',
'1,5',
'kilos',
'conejo',
'\n',
...]
I would like to get a dict like this:
my_dic=[
{"name":"aceite" ,"qt":50 ,"unit": "ccs"},
{"name":"laurel" ,"qt":1 ,"unit": "hoja"},
{"name":"ajos" ,"qt":1 ,"unit": "cabeza"},
{"name":"vino" ,"qt":1 ,"unit": "vaso"},
{"name":"conejo" ,"qt":1,5 ,"unit": "kilos"},
...]
I have been trying things but it was all a disaster.
Any ideas?
Thanks in advance!!
So first, you want to remove the newlines from your original list:
ingredients = [i for i in ingredients if i is not '\n']
Then, each ingredient name is every third element in the ingredients list starting from the third element. Likewise for the quantity and unit, starting from the second and first elements, respectively:
names = ingredients[2::3]
units = ingredients[1::3]
qts = ingredients[::3]
Then, iterate through these lists and construct the data structure you specified (which is not actually a dict but a list of dicts):
my_list = []
for i in range(len(names)):
my_dict = {"name":names[i],"qt":qts[i],"unit":units[i]}
my_list.append(my_dict)
There are a lot of ways to compress all of the above, but I have written it for comprehensibility.
This doesn't produce a dictionary, but it does give you the output that you specify in the question:
# Strip out the \n values (can possibly do this with a .strip() in the input stage)
ingredients = [value for value in ingredients if value != '\n']
labels = ['qt', 'unit', 'name']
my_dic = [dict(zip(labels, ingredients[i:i+3])) for i in range(0, len(ingredients), 3)]
my_dic contains:
[{'qt': '50', 'unit': 'ccs', 'name': 'aceite'},
{'qt': '1', 'unit': 'hoja', 'name': 'laurel'},
{'qt': '1', 'unit': 'cabeza', 'name': 'ajos'},
{'qt': '1', 'unit': 'vaso', 'name': 'vino'},
{'qt': '1,5', 'unit': 'kilos', 'name': 'conejo'}]
You can clean you list with filter to remove the \n characters and then zip() it together to collect your items together. This makes a quick two-liner:
l = filter(lambda w: w != '\n', ingredients)
result = [{'name': name, 'qt':qt, 'unit': unit}
for qt, unit, name in zip(l, l, l)]
result:
[{'name': 'aceite', 'qt': '50', 'unit': 'ccs'},
{'name': 'laurel', 'qt': '1', 'unit': 'hoja'},
{'name': 'ajos', 'qt': '1', 'unit': 'cabeza'},
{'name': 'vino', 'qt': '1', 'unit': 'vaso'},
{'name': 'conejo', 'qt': '1,5', 'unit': 'kilos'}]
How about:
ingredients = (list)(filter(lambda a: a != '\n', ingredients))
ing_organized = []
for i in range (0, len(ingredients) , 3):
curr_dict = {"name": ingredients[i+2] ,"qt": ingredients[i] ,"unit": ingredients[i+1]}
ing_organized.append(curr_dict)
I just removed '\n' elements from the list as they didn't seem to have meaning.
lst = [['111', 'kam'],['222', 'Van']]
Header = ['ID', 'Name']
I want to convert the above list to dictionary based on the Headers. I can do this simply using for loop by taking each element in loop and append to some new list one by one.
But, I want to achieve the same without using loop to prevent from performance issue.
Is there any way to do that?
Expected Output:
[{'ID' : '111', 'Name' : 'Kam'},{'ID' : '222', 'Name' : 'Van'}]
You can use a list comprehension:
lst = [['111', 'kam'],['222', 'Van']]
Header = ['ID', 'Name']
result = [dict(zip(Header, row)) for row in lst]
print(result)
Output:
[{'ID': '111', 'Name': 'kam'}, {'ID': '222', 'Name': 'Van'}]
I have two different lists with dictionaries:
first = [{'id': '1'}, {'id': '2'}, {'id': '3'}]
second = [{'user_id': '1'}, {'user_id': '2'}]
I want something like:
# This is pseudocode
first (id) - second (user_id) = [{'id': '3'}]
Is this possible on python?
I know that it is possible by using multiple loop operators, but is there more elegant method of solving this problem, like using lambdas or something?
One way is to use a nested list comprehension as following:
In [9]: [d1 for d1 in first if not any(d2['user_id'] == d1['id'] for d2 in second)]
Out[9]: [{'id': '3'}]
But as a more Pythonic way it's better to use set operations and a list comprehension:
In [13]: f = {d['id'] for d in first}
In [14]: s = {d['user_id'] for d in second}
In [15]: result = [{'id': i} for i in f - s]
In [16]: result
Out[16]: [{'id': '3'}]
This is one approach. Using a list comprehension and lambda.
first = [{'id': '1'}, {'id': '2'}, {'id': '3'}]
second = [{'user_id': '1'}, {'user_id': '2'}]
checkVal = map(lambda d: d['user_id'], second)
print([i for i in first if i["id"] not in checkVal])
Output:
[{'id': '3'}]
I have a list of dicts.
dictList = [
{'name': 'some name'},
{'name': 'some other name'},
{'age': 'some age'},
{'last_name': 'some last name'}
]
In that list of dicts each dict has one key and one value for that key, as shown above.
I need to create a dict that has the keys from all the dicts and each value for every key is a set with item values from the list of dicts. In the example, it'd be something like this:
expected_dict = {
'name': ['some name', 'some other name'],
'age': ['some age'],
'last_name': ['some last name']
}
How can I do this in Python?
collections.defaultdict is one way:
from collections import defaultdict
d = defaultdict(list)
dictList = [
{'name': 'some name'},
{'name': 'some other name'},
{'age': 'some age'},
{'last_name': 'some last name'}
]
for i in dictList:
for k, v in i.items():
d[k].append(v)
# defaultdict(list,
# {'age': ['some age'],
# 'last_name': ['some last name'],
# 'name': ['some name', 'some other name']})
You can use the builtin setdefault() function.
dictList = [
{'name': 'some name'},
{'name': 'some other name'},
{'age': 'some age'},
{'last_name': 'some last name'}
]
expected_dict = {}
for dictionary in dictList:
for key, val in dictionary.items():
expected_dict.setdefault(key, []).append(val)
print(expected_dict)
Output:
{
'name': ['some name', 'some other name'],
'age': ['some age'],
'last_name': ['some last name']
}
Note: Using collections.defaultdict (as shown in this answer) is simpler and faster than using dict.setdefault().
From the documentation:
Working of collections.defaultdict:
When each key is encountered for the first time, it is not already in the mapping; so an entry is automatically created using the default_factory function which returns an empty list. The list.append() operation then attaches the value to the new list. When keys are encountered again, the look-up proceeds normally (returning the list for that key) and the list.append() operation adds another value to the list. This technique is simpler and faster than an equivalent technique using dict.setdefault().
bigD = {}
for element in dictList:
for key in element:
if key in bigD:
bigD[key].append(element[key])
else:
bigD[key] = element[key]
You can use itertools.groupby:
import import itertools
dictList = [
{'name': 'some name'},
{'name': 'some other name'},
{'age': 'some age'},
{'last_name': 'some last name'}
]
new_list = {a:[c for [[_, c]] in b] for a, b in itertools.groupby(map(lambda x:x.items(), dictList), key=lambda x:x[0][0])}
Output:
{'age': ['some age'], 'last_name': ['some last name'], 'name': ['some name', 'some other name']}
Very simply.
dict = {}
list = [1,2,3]
dict['numbs'] = list
print(dict)
Output :
{'numbs': [1, 2, 3]}