How to insert key-value pair into dictionary at a specified position? - python

How would I insert a key-value pair at a specified location in a python dictionary that was loaded from a YAML document?
For example if a dictionary is:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
I wish to insert the element 'Phone':'1234'
before 'Age', and after 'Name' for example. The actual dictionary I shall be working on is quite large (parsed YAML file), so deleting and reinserting might be a bit cumbersome (I don't really know).
If I am given a way of inserting into a specified position in an OrderedDict, that would be okay, too.

On python < 3.7 (or cpython < 3.6), you cannot control the ordering of pairs in a standard dictionary.
If you plan on performing arbitrary insertions often, my suggestion would be to use a list to store keys, and a dict to store values.
mykeys = ['Name', 'Age', 'Class']
mydict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} # order doesn't matter
k, v = 'Phone', '123-456-7890'
mykeys.insert(mykeys.index('Name')+1, k)
mydict[k] = v
for k in mykeys:
print(f'{k} => {mydict[k]}')
# Name => Zara
# Phone => 123-456-7890
# Age => 7
# Class => First
If you plan on initialising a dictionary with ordering whose contents are not likely to change, you can use the collections.OrderedDict structure which maintains insertion order.
from collections import OrderedDict
data = [('Name', 'Zara'), ('Phone', '1234'), ('Age', 7), ('Class', 'First')]
odict = OrderedDict(data)
odict
# OrderedDict([('Name', 'Zara'),
# ('Phone', '1234'),
# ('Age', 7),
# ('Class', 'First')])
Note that OrderedDict does not support insertion at arbitrary positions (it only remembers the order in which keys are inserted into the dictionary).

You will have to initialize your dict as OrderedDict. Create a new empty OrderedDict, go through all keys of the original dictionary and insert before/after when the key name matches.
from pprint import pprint
from collections import OrderedDict
def insert_key_value(a_dict, key, pos_key, value):
new_dict = OrderedDict()
for k, v in a_dict.items():
if k==pos_key:
new_dict[key] = value # insert new key
new_dict[k] = v
return new_dict
mydict = OrderedDict([('Name', 'Zara'), ('Age', 7), ('Class', 'First')])
my_new_dict = insert_key_value(mydict, "Phone", "Age", "1234")
pprint(my_new_dict)

Had the same issue and solved this as described below without any additional imports being required and only a few lines of code.
Tested with Python 3.6.9.
Get position of key 'Age' because the new key value pair should get inserted before
Get dictionary as list of key value pairs
Insert new key value pair at specific position
Create dictionary from list of key value pairs
mydict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print(mydict)
# {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
pos = list(mydict.keys()).index('Age')
items = list(mydict.items())
items.insert(pos, ('Phone', '123-456-7890'))
mydict = dict(items)
print(mydict)
# {'Name': 'Zara', 'Phone': '123-456-7890', 'Age': 7, 'Class': 'First'}
Edit 2021-12-20:
Just saw that there is an insert method available ruamel.yaml, see the example from the project page:
import sys
from ruamel.yaml import YAML
yaml_str = """\
first_name: Art
occupation: Architect # This is an occupation comment
about: Art Vandelay is a fictional character that George invents...
"""
yaml = YAML()
data = yaml.load(yaml_str)
data.insert(1, 'last name', 'Vandelay', comment="new key")
yaml.dump(data, sys.stdout)

This is a follow-up on nurp's answer. Has worked for me, but offered with no warranty.
# Insert dictionary item into a dictionary at specified position:
def insert_item(dic, item={}, pos=None):
"""
Insert a key, value pair into an ordered dictionary.
Insert before the specified position.
"""
from collections import OrderedDict
d = OrderedDict()
# abort early if not a dictionary:
if not item or not isinstance(item, dict):
print('Aborting. Argument item must be a dictionary.')
return dic
# insert anywhere if argument pos not given:
if not pos:
dic.update(item)
return dic
for item_k, item_v in item.items():
for k, v in dic.items():
# insert key at stated position:
if k == pos:
d[item_k] = item_v
d[k] = v
return d
d = {'A':'letter A', 'C': 'letter C'}
insert_item(['A', 'C'], item={'B'})
## Aborting. Argument item must be a dictionary.
insert_item(d, item={'B': 'letter B'})
## {'A': 'letter A', 'C': 'letter C', 'B': 'letter B'}
insert_item(d, pos='C', item={'B': 'letter B'})
# OrderedDict([('A', 'letter A'), ('B', 'letter B'), ('C', 'letter C')])

Would this be "pythonic"?
def add_item(d, new_pair, old_key): #insert a newPair (key, value) after old_key
n=list(d.keys()).index(old_key)
return {key:d.get(key,new_pair[1]) for key in list(d.keys())[:n+1] +[new_pair[0]] + list(d.keys())[n+1:] }
INPUT: new_pair=('Phone',1234) , old_key='Age'
OUTPUT: {'Name': 'Zara', 'Age': 7, 'Phone': 1234, 'Class': 'First'}

Simple reproducible example (using zip() for unpacking and packing)
### Task - Insert 'Bangladesh':'Dhaka' after 'India' in the capitals dictinary
## Given dictionary
capitals = {'France':'Paris', 'United Kingdom':'London', 'India':'New Delhi',
'United States':'Washington DC','Germany':'Berlin'}
## Step 1 - Separate into 2 lists containing : 1) keys, 2) values
country, cap = (list(tup) for tup in zip(*capitals.items()))
# or
country, cap = list(map(list, zip(*capitals.items())))
print(country)
#> ['France', 'United Kingdom', 'India', 'United States', 'Germany']
print(cap)
#> ['Paris', 'London', 'New Delhi', 'Washington DC', 'Berlin']
## Step 2 - Find index of item before the insertion point (from either of the 2 lists)
req_pos = country.index('India')
print(req_pos)
#> 2
## Step 3 - Insert new entry at specified position in both lists
country.insert(req_pos+1, 'Bangladesh')
cap.insert(req_pos+1, 'Dhaka')
print(country)
#> ['France', 'United Kingdom', 'India', 'Bangladesh', 'United States', 'Germany']
print(cap)
#> ['Paris', 'London', 'New Delhi', 'Dhaka', 'Washington DC', 'Berlin']
## Step 4 - Zip up the 2 lists into a dictionary
capitals = dict(zip(country, cap))
print(capitals)
#> {'France': 'Paris', 'United Kingdom': 'London', 'India': 'New Delhi', 'Bangladesh': 'Dhaka', 'United States': 'Washington DC', 'Germany': 'Berlin'}

Once your have used load() (without option Loader=RoundTripLoader) and your data is in a dict() it is to late, as the order that was available in the YAML file is normally gone (the order depending on the actual keys used, the python used (implementation, version and possible compile options).
What you need to do is use round_trip_load():
import sys
from ruamel import yaml
yaml_str = "{'Name': 'Zara', 'Age': 7, 'Class': 'First'}"
data = yaml.round_trip_load(yaml_str)
pos = list(data.keys()).index('Age') # determine position of 'Age'
# insert before position of 'Age'
data.insert(pos, 'Phone', '1234', comment='This is the phone number')
data.fa.set_block_style() # I like block style
yaml.round_trip_dump(data, sys.stdout)
this will invariable give:
Name: Zara
Phone: '1234' # This is the phone number
Age: 7
Class: First
Under the hood round_trip_dump() transparently gives you back a subclass of orderddict to make this possible (which actual implementation is dependent on your Python version).

Since your elements comes in pairs, I think this will could work.
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
new_element = { 'Phone':'1234'}
dict = {**dict,**new_element}
print(dict)
This is the output I got:
{'Name': 'Zara', 'Age': 7, 'Class': 'First', 'Phone': '1234'}

Related

Python: Way to build a dictionary with a variable key and append to a list as the value inside a loop

I have a list of dictionaries. I want to loop through this list of dictionary and for each specific name (an attribute inside each dictionary), I want to create a dictionary where the key is the name and the value of this key is a list which dynamically appends to the list in accordance with a specific condition.
For example, I have
d = [{'Name': 'John', 'id': 10},
{'Name': 'Mark', 'id': 21},
{'Name': 'Matthew', 'id': 30},
{'Name': 'Luke', 'id': 11},
{'Name': 'John', 'id': 20}]
I then built a list with only the names using names=[i['Name'] for i in dic1] so I have a list of names. Notice John will appear twice in this list (at the beginning and end). Then, I want to create a for-loop (for name in names), which creates a dictionary 'ID' that for its value is a list which appends this id field as it goes along.
So in the end I'm looking for this ID dictionary to have:
John: [10,20]
Mark: [21]
Matthew: [30]
Luke: [11]
Notice that John has a list length of two because his name appears twice in the list of dictionaries.
But I can't figure out a way to dynamically append these values to a list inside the for-loop. I tried:
ID={[]} #I also tried with just {}
for name in names:
ID[names].append([i['id'] for i in dic1 if i['Name'] == name])
Please let me know how one can accomplish this. Thanks.
Don't loop over the list of names and go searching for every one in the list; that's very inefficient, since you're scanning the whole list all over again for every name. Just loop over the original list once and update the ID dict as you go. Also, if you build the ID dict first, then you can get the list of names from it and avoid another list traversal:
names = ID.keys()
The easiest solution for ID itself is a dictionary with a default value of the empty list; that way ID[name].append will work for names that aren't in the dict yet, instead of blowing up with a KeyError.
from collections import defaultdict
ID = defaultdict(list)
for item in d:
ID[item['Name']].append(item['id'])
You can treat a defaultdict like a normal dict for almost every purpose, but if you need to, you can turn it into a plain dict by calling dict on it:
plain_id = dict(ID)
The Thonnu has a solution using get and list concatenation which works without defaultdict. Here's another take on a no-import solution:
ID = {}
for item in d:
name, number = item['Name'], item['id']
if name in ID:
ID[name].append(number)
else:
ID[name] = [ number ]
Using collections.defaultdict:
from collections import defaultdict
out = defaultdict(list)
for item in dic1:
out[item['Name']].append(item['id'])
print(dict(out))
Or, without any imports:
out = {}
for item in dic1:
out[item['Name']] = out.get(item['Name'], []) + [item['id']]
print(out)
Or, with a list comprehension:
out = {}
[out.update({item['Name']: out.get(item['Name'], []) + [item['id']]}) for item in dic1]
print(out)
Output:
{'John': [10, 20], 'Mark': [21], 'Matthew': [30], 'Luke': [11]}
dic1 = [{'Name': 'John', 'id': 10}, {'Name': 'Mark', 'id': 21}, {'Name': 'Matthew', 'id': 30}, {'Name': 'Luke', 'id': 11}, {'Name': 'John', 'id': 20}]
id_dict = {}
for dic in dic1:
key = dic['Name']
if key in id_dict:
id_dict[key].append(dic['id'])
else:
id_dict[key] = [dic['id']]
print(id_dict) # {'John': [10, 20], 'Mark': [21], 'Matthew': [30], 'Luke': [11]}
You can use defaultdict for this to initiate a dictionary with a default value. In this case the default value will be empty list.
from collections import defaultdict
d=defaultdict(list)
for item in dic1:
d[item['Name']].append(item['id'])
Output
{'John': [10, 20], 'Mark': [21], 'Matthew': [30], 'Luke': [11]} # by converting (not required) into pure dict dict(d)
You can do in a easy version
dic1=[{'Name': 'John', 'id':10}, {'Name': 'Mark', 'id':21},{'Name': 'Matthew', 'id':30}, {'Name': 'Luke', 'id':11}, {'Name': 'John', 'id':20}]
names=[i['Name'] for i in dic1]
ID = {}
for i, name in enumerate(names):
if name in ID:
ID[name].append(dic1[i]['id'])
else:
ID[name] = [dic1[i]['id']]
print(ID)

How do i access a dictionary after using loops to convert some lists to dictionary? The code is below

INSTRUCTION:
The data is organized such that the data at each index, from 0 to 33, corresponds to the same hurricane.
For example, names[0] yield the “Cuba I” hurricane, which occurred in months[0] (October) years[0] (1924).
Write a function that constructs a dictionary made out of the lists, where the keys of the dictionary are the names of the hurricanes, and the values are dictionaries themselves containing a key for each piece of data (Name, Month, Year, Max Sustained Wind, Areas Affected, Damage, Death) about the hurricane.
Thus the key "Cuba I" would have the value: {'Name': 'Cuba I', 'Month': 'October', 'Year': 1924, 'Max Sustained Wind': 165, 'Areas Affected': ['Central America', 'Mexico', 'Cuba', 'Florida', 'The Bahamas'], 'Damage': 'Damages not recorded', 'Deaths': 90}.
THESE ARE THE LISTS:
names = ['Cuba I', 'San Felipe II Okeechobee', 'Cuba II']
months = ['October', 'September', 'September']
years = [1924, 1928, 1932]
max_sustained_winds = [165, 160, 160]
areas_affected = [['Central America', 'Mexico', 'Cuba', 'Florida', 'The Bahamas'], ['Lesser Antilles', 'The Bahamas', 'United States East Coast', 'Atlantic Canada'], ['The Bahamas', 'Northeastern United States']]
damages = ['Damages not recorded', '100M', 'Damages not recorded', '40M']
deaths = [90,4000,16]
THE CODE I HAVE TRIED:
hurricane_records = list(zip(names, months, years, max_sustained_winds, areas_affected, update_damages(), deaths))
dict1 = {}
strongest_hurricane_records = {}
for i in range(len(names)):
dict1["Name"] = hurricane_records[i][0]
dict1["Month"] = hurricane_records[i][1]
dict1["Year"] = hurricane_records[i][2]
dict1["Max Sustained Wind"] = hurricane_records[i][3]
dict1["Areas Affected"] = hurricane_records[i][4]
dict1["Damage"] = hurricane_records[i][5]
dict1["Deaths"] = hurricane_records[i][6]
strongest_hurricane_records[names[i]] = dict1
print(strongest_hurricane_records["Cuba I"])
My problem here is that when I tried to access the dictionary "Cuba I", instead of printing the values of "Cuba I" dictionary, it is printing the last dictionary which is this:
{'Cuba II', 'September', 1928, 160, ['Lesser Antilles', 'The Bahamas', 'United States East Coast', 'Atlantic Canada'], '100M', 4000}
The problem is that you have dict1 = {} outside of the for loop, so only one dictionary will be created, and each iteration of loop will modify the same dictionary. Simply move dict1 = {} into the loop to re-initialize it for each hurricane:
strongest_hurricane_records = {}
for i in range(len(names)):
dict1 = {} # Now dict1 is unique for each loop iteration
dict1["Name"] = ...
strongest_hurricane_records[names[i]] = dict1
update_damages() isn't reproducible so I made my own lists which are similar to yours. Remember to run your code and fix errors before posting the minimal working example.
If I understand correctly you want to create a nested dictionary, i.e. a dictionary which contains other dictionaries.
I give a simplified version. You can find more advanced in other very relevant questions like in How to zip three lists into a nested dict.
# Outer dictionary:
genders = ['male', 'female']
# Inner dictionary:
keys = ['name', 'surname', 'age']
names = ['Bob', 'Natalie']
surnames = ['Blacksmith', 'Smith']
ages = [10, 20]
inner_dictionaries = [dict(zip(keys, [names[i],
surnames[i],
ages[i]]))
for i, elem in enumerate(names)]
# [{'name': 'Bob', 'surname': 'Blacksmith', 'age': 10},
# {'name': 'Natalie', 'surname': 'Smith', 'age': 20}]
outer_dictionaries = dict((keys, values)
for keys, values in
zip(genders, inner_dictionaries))
# {'male': {'name': 'Bob', 'surname': 'Blacksmith', 'age': 10},
# 'female': {'name': 'Natalie', 'surname': 'Smith', 'age': 20}}
By the way avoid range(len()) in a for loop if you want to loop like a native (also from R. Hettinger). Moving on, the inner_dictionaries comes from this for loop:
for index, element in enumerate(names):
print(dict(zip(keys, [names[index], surnames[index], ages[index]])))
You can make a list of all the values then use a for loop and then convert each value into dictionary using dict(value) and then append these results into another dictionary using .update() function:
Features = [all features]
Dict = {}
for f in Features:
Dict.update(dict(f))
else:
print(Dict)

How can I use list comprehension to separate values in a dictionary?

name=[]
age=[]
address=[]
...
for line in pg:
for key,value in line.items():
if key == 'name':
name.append(value)
elif key == 'age':
age.append(value)
elif key == 'address':
address.append(value)
.
.
.
Is it possible to use list comprehension for above code because I need to separate lots of value in the dict? I will use the lists to write to a text file.
Source Data:
a = [{'name': 'paul', 'age': '26.', 'address': 'AU', 'gender': 'male'},
{'name': 'mei', 'age': '26.', 'address': 'NY', 'gender': 'female'},
{'name': 'smith', 'age': '16.', 'address': 'NY', 'gender': 'male'},
{'name': 'raj', 'age': '13.', 'address': 'IND', 'gender': 'male'}]
I don't think list comprehension will be a wise choice because you have multiple lists.
Instead of making multiple lists and appending to them the value if the key matches you can use defaultdict to simplify your code.
from collections import defaultdict
result = defaultdict(list)
for line in pg:
for key, value in line.items():
result[key].append(value)
You can get the name list by using result.get('name')
['paul', 'mei', 'smith', 'raj']
This probably won't work the way you want: Your'e trying to assign the three different lists, so you would need three different comprehensions. If your dict is large, this would roughly triple your execution time.
Something straightforward, such as
name = [value for for key,value in line.items() if key == "name"]
seems to be what you'd want ... three times.
You can proceed as :
pg=[{"name":"name1","age":"age1","address":"address1"},{"name":"name2","age":"age2","address":"address2"}]
name=[v for line in pg for k,v in line.items() if k=="name"]
age=[v for line in pg for k,v in line.items() if k=="age"]
address=[v for line in pg for k,v in line.items() if k=="address"]
In continuation with Vishal's answer, please dont use defaultdict. Using defaultdict is a very bad practice when you want to catch keyerrors. Please use setdefault.
results = dict()
for line in pg:
for key, value in line.items():
result.setdefault(key, []).append(value)
Output
{
'name': ['paul', 'mei', 'smith', 'raj'],
'age': [26, 26, 26, 13],
...
}
However, note that if all dicts in pg dont have the same keys, you will lose the relation/correspondence between the items in the dict
Here is a really simple solution if you want to use pandas:
import pandas as pd
df = pd.DataFrame(a)
name = df['name'].tolist()
age = df['age'].tolist()
address = df['address'].tolist()
print(name)
print(age)
print(address)
Output:
['paul', 'mei', 'smith', 'raj']
['26.', '26.', '16.', '13.']
['AU', 'NY', 'NY', 'IND']
Additionally, if your end result is a text file, you can skip the list creation and write the DataFrame (or parts thereof) directly to a CSV with something as simple as:
df.to_csv('/path/to/output.csv')

sort a list of dictionaries based on explicitly defined order of keys

I have a list of dictionary for ex:
names = [{'Mark':'Volvo'}, {'John':'BMW'}, {'Eliza':'Merci'}, {'Calen':'Audi'}]
I would like to set the explicit ordering by the key names of the dictionary.
For example if I give this order:
['John','Mark','Calen','Eliza']
The expected output would be:
[{'John':'BMW'},{'Mark':'Volvo'},{'Calen':'Audi'},{'Eliza':'Merci'}]
I want to add a custom logic order. To be displayed through the template by their names, based on how I defined the order of their names.
Similar to Is there a way to sort a list of string by a “predicate” list?: Since names is a list of dictionaries with just one key-value pair each, use the index of the person's name in the order list as the key for the sort:
>>> names = [{'Mark': 'Volvo'}, {'John': 'BMW'}, {'Eliza': 'Merci'}, {'Calen' :'Audi'}]
>>> order = ['John', 'Mark', 'Calen', 'Eliza']
>>>
>>> # with `sorted()`
>>> sorted(names, key=lambda d: order.index(list(d.keys())[0]))
[{'John': 'BMW'}, {'Mark': 'Volvo'}, {'Calen': 'Audi'}, {'Eliza': 'Merci'}]
>>>
>>> # or with `list.sort()`
>>> names.sort(key=lambda d: order.index(list(d.keys())[0]))
>>> names
[{'John': 'BMW'}, {'Mark': 'Volvo'}, {'Calen': 'Audi'}, {'Eliza': 'Merci'}]
dict.keys() is not not subscriptable, so dict.keys()[0] doesn't work. So first convert that to a list and then use its one-and-only key list(dict.keys())[0]. That would give 'Mark', 'John', etc. Then get the index of that person's name in the order list. Note: it will fail if a person is not listed in order.
Even if names is a list of dictionaries with more than one key-value pair each, as long as the person's name is the first key, it will still work as of Python 3.7/3.6. See the note below this item:
Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.
>>> names = [{'Mark': 'Volvo', 'age': 30},
... {'John': 'BMW', 'age': 40},
... {'Eliza': 'Merci', 'age': 50},
... {'Calen': 'Audi', 'age': 60}]
>>> sorted(names, key=lambda d: order.index(list(d.keys())[0]))
[{'John': 'BMW', 'age': 40}, {'Mark': 'Volvo', 'age': 30}, {'Calen': 'Audi', 'age': 60}, {'Eliza': 'Merci', 'age': 50}]
>>>
First, if your dictionaries only have one entry, tuples seem to be a better choice for this data:
>>> names = [('Mark', 'Volvo'), ('John', 'BMW'), ('Eliza', 'Merci'), ('Calen', 'Audi')]
Now, given this order:
>>> order = ['John', 'Mark', 'Calen', 'Eliza']
you can create a dict that maps the names to the indices:
>>> order_map = { k: v for v, k in enumerate(order) }
>>> order_map
{'John': 0, 'Mark': 1, 'Calen': 2, 'Eliza': 3}
and use it in a key function for sort:
>>> names.sort(key=lambda v: order_map[v[0]])
>>> names
[('John', 'BMW'), ('Mark', 'Volvo'), ('Calen', 'Audi'), ('Eliza', 'Merci')]
names = [{'Mark':'Volvo'}, {'John':'BMW'}, {'Eliza':'Merci'}, {'Calen':'Audi'}]
ordered_keys = ['John','Mark','Calen','Eliza']
sorted_names = [name for key in ordered_keys for name in names if key in name]
It iterates over the ordered_keys in order and extracts any name in the list of dict that has that key.

Dict from list of dicts

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]}

Categories