How append multiple dicto into a one dict python - python

I develop with python and i have a multiple dictionnary like:
Dict1: {‘hi’:’340’, ‘hello’:’570’, ’me’:´800’}
Dict1: {‘hi’:’200’, ‘hello’:’100’, ’me’:´389’}
And i would like to add them together into a dict like:
Dict_new= { {‘hi’:’340’,‘hello’:’570’, ’me’:´800’}, {‘hi’:’200’, ‘hello’:’100’, ’me’:´389’}}
Finally i would likt to have this output:
{‘elements’:{{‘hi’:’340’,‘hello’:’570’,
’me’:´800’},
{‘hi’:’200’, ‘hello’:’100’,
’me’:´389’}}}
So what is the best mannee to do this ?

Instead of using a set, please consider using a list which will store your dictionaries.
newDict = {}
newDict['element'] = [dict1,dict2]
output
{'elements': [{'hi': '340', 'hello': '570', 'me': '800'}, {'hi': '200', 'hello': '100', 'me': '389'}]}

Related

convert list of dict into dict python - pythonic way

input:
list = [{'key': '1234', 'value': 100.00}, {'key': '2345', 'value': 200.0}]
output:
{'1234': 100.00, '2345': 200.0}
I now this can be achieved by looping over. Is there any pythonic way to do the same?
You're right that a loop would be straightforward.
result = {}
for curr in lst:
result[curr['key']] = result[curr['value']]
We can shorten it a bit with a dictionary comprehension. This says the same thing but more compactly
result = { curr['key']: curr['value'] for curr in lst }
By "pythonic", I take that to mean using things like dict comprehension:
list = [{'key': '1234', 'value': 100.00}, {'key': '2345', 'value': 200.0}]
output = {item["key"]: item["value"] for item in list}
print(output) # {'1234': 100.00, '2345': 200.0}
By the way, you might want to rename list to something else, because list is an internal python function.
Just for funsies, a method that involves executing no Python-level code per-item:
from operator import itemgetter
lst = [{'key': '1234', 'value': 100.00}, {'key': '2345', 'value': 200.0}]
dct = dict(map(itemgetter('key', 'value'), lst))
The itemgetter, when passed a dict from lst, extracts the key and value and returns them as a tuple. map ensures this is done for each dict in lst, and the dict constructor knows how to turn an iterable of two-tuples into a new dict, all without executing a single byte code for any given item (all bytecode involved is fixed overhead to set everything up, then the map iterator is run to exhaustion to populate the dict without returning control to the byte code eval loop, as long as all keys and values involved are built-ins implemented in C).
Just use the values of each dict to make the new dict:
dict(map(dict.values, lst))
{'1234': 100.0, '2345': 200.0}
Caution the dicts need to be in key/value order like in your example for this to work properly. Which also means this will work fine in Python 3 but you will need to use an collections.OrderedDict in python 2.7
It can be writed in one line like this with nested comprehension:
data = [{'key': '1234', 'value': 100.00}, {'key': '2345', 'value': 200.0}]
new_dict = {r[0]: r[1] for r in [list(d.values()) for d in data]}
Thanks for ShadowRanger it can be simplified to:
new_dict = dict(d.values() for d in data)
It works only with Python 3.7+ with ordered dicts.

accessing a dictionary from a list of dictionaries using value

I have list of dictionaries of
a = [{'id':'1','name':'john'}, {'id':'2','name':'johns'}, {'id':'3','name':'rock'}
I want to display the dictionary of using the id value '2' to search the dictionary and the wanted output is like this
{'id':'2','name':'johns'}
How to display the dictionary to be like that?
You can use list comprehension, in O(n):
a = [{'id':'1','name':'john'}, {'id':'2','name':'johns'}, {'id':'3','name':'rock'}]
# [{'id': '2', 'name': 'johns'}]
print([d for d in a if d['id'] == '2'])
However representing data as dictionary is more efficient, in O(1):
a = {'1': {'name' : 'john'}, '2': {'name' : 'johns'}, '3': {'name' : 'rock'}}
# {'name': 'johns'}
print(a['2'])

How to convert list of dicts to dicts?

I have a list of dict that I am struggling to change to list of dicts:
x = [
{ # begin first and only dict in list
'11': [{'bb': '224', 'cc': '14'}, {'bb': '254', 'cc': '16'}]
, '22': [{'bb': '824', 'cc': '19'}]
}
]
Which currently has a length of 1. i.e.:
print(len(x)) # 1
I intend to change it to list of dicts. i.e.:
desired = [
{ # begin first dict in list
'11': [{'bb': '224', 'cc': '14'}, {'bb': '254', 'cc': '16'}]
}
, { # begin second dict in list
'22': [{'bb': '824', 'cc': '19'}]
}
]
print(len(desired)) # 2
What I tried:
dd = {}
for elem in x:
for k,v in elem.items():
dd[k] = v
print([dd])
print(len(dd)) # 2
Is there a better way or perhaps more efficient way?
Like others mentioned, there is nothing "wrong" with what you've tried. However, you might be interested in trying a list comprehension:
x_desired = [{k: v} for i in x for k, v in i.items()]
Like your attempted approach, this is effectively 2 for loops, the second nested within the first. In general, list comprehensions are considered fast and Pythonic.
Do you want the result to be 2 as you"ve got two keys (11 & 22) ?
then try this:
print(len(x[0]))

Pythonic way of switching nested dictionary keys with nested values

In short I'm working with a nested dictionary structured like this:
nested_dict = {'key1':{'nestedkey1': 'nestedvalue1'}}
I'm trying to find a pythonic way of switching the keys with the nested values, so it would look like this:
nested_dict = {'nestedvalue1':{'nestedkey1': 'key1'}}
I'm also trying to rename the nested key values, so ultimately the dictionary would look like this:
nested_dict = {'nestedvalue1':{'NEWnestedkey1': 'key1'}}
This is closer to what I'm working with:
original_dict = {
'buford': {'id': 1},
'henley': {'id': 2},
'emi': {'id': 3},
'bronc': {'id': 4}
}
I want it to look like this:
new_dict = {
1: {'pet': 'buford'},
2: {'pet': 'henley'},
3: {'pet': 'emi'},
4: {'pet': 'bronc'}
}
Is there a way to do this in one line using a dictionary comprehension? I'm trying to get the very basics here and avoid having to use things like itertools.
You can use a dictionary comprehension to achieve this, 'swapping' things round as you build it:
new_dict = {v['id']: {'pet': k} for k, v in original_dict.items()}
To expand it to a for loop, it'd look something like:
new_dict = {}
for k, v in original_dict.items():
new_dict[v['id']] = {'pet': k}
Note that both cases obviously rely on the 'id' value being unique, or the key will be overwritten for each occurrence.
For a more generic solution, you can try this:
def replace(d, change_to = 'pet'):
return {b.values()[0]:{change_to:a} for a, b in d.items()}
Output:
{1: {'pet': 'buford'}, 2: {'pet': 'henley'}, 3: {'pet': 'emi'}, 4: {'pet': 'bronc'}}

Split list elements to key/val dictionary

I have this:
query='id=10&q=7&fly=none'
and I want to split it to create a dictionary like this:
d = { 'id':'10', 'q':'7', 'fly':'none'}
How can I do it with little code?
By splitting twice, once on '&' and then on '=' for every element resulting from the first split:
query='id=10&q=7&fly=none'
d = dict(i.split('=') for i in query.split('&'))
Now, d looks like:
{'fly': 'none', 'id': '10', 'q': '7'}
In your case, the more convenient way would be using of urllib.parse module:
import urllib.parse as urlparse
query = 'id=10&q=7&fly=none'
d = {k:v[0] for k,v in urlparse.parse_qs(query).items()}
print(d)
The output:
{'id': '10', 'q': '7', 'fly': 'none'}
Note, that urlparse.parse_qs() function would be more useful if there multiple keys with same value in a query string. Here is an example:
query = 'id=10&q=7&fly=none&q=some_identifier&fly=flying_away'
d = urlparse.parse_qs(query)
print(d)
The output:
{'q': ['7', 'some_identifier'], 'id': ['10'], 'fly': ['none', 'flying_away']}
https://docs.python.org/3/library/urllib.parse.html#urllib.parse.parse_qs
This is what I came up with:
dict_query = {}
query='id=10&q=7&fly=none'
query_list = query.split("&")
for i in query_list:
query_item = i.split("=")
dict_query.update({query_item[0]: query_item[1]})
print(dict_query)
dict_query returns what you want. This code works by splitting the query up into the different parts, and then for each of the new parts, it splits it by the =. It then updates the dict_query with each new value. Hope this helps!

Categories