Related
I found many different solutions for doing so for single case but not for pandas Series.
I would like to change this
col1
0 [{'a':2, 'b':3, 'c':9}]
1 [{'a':1, 'b':0, 'c':8}]
2 [{'a':4, 'b': 5, 'c':12}]
3 [{'a':3, 'b':6, 'c':11}]
into
col1
0 {'a':2, 'b':3, 'c':9}
1 {'a':1, 'b':0, 'c':8}
2 {'a':4, 'b': 5, 'c':12}
3 {'a':3, 'b':6, 'c':11}
Thanks
If there is one element list select by indexing for remove []:
df['col'] = df['col'].str[0]
If values are strings repr of dicts:
import ast
df['col'] = df['col'].apply(ast.literal_eval).str[0]
print (df)
col
0 {'a': 2, 'b': 3, 'c': 9}
1 {'a': 1, 'b': 0, 'c': 8}
2 {'a': 4, 'b': 5, 'c': 12}
3 {'a': 3, 'b': 6, 'c': 11}
i'm trying my code. I'm confused..How to combine these 2 dictionaries so that the value of the results is like this?
1 A 18
5 B 14
3 C 15
7 D 20
for code
d= {'A': 1, 'B': 5, 'C': 3, 'D': 7}
e= {'A': 18, 'B': 14, 'C': 15, 'D': 20}
for k,v in d.items():
print (v)
for i,(k, v) in enumerate(e.items()):
print(i,k, v)
i don't understand. Please help me. Thanks!
You can do this:
d = {'A': 1, 'B': 5, 'C': 3, 'D': 7}
e = {'A': 18, 'B': 14, 'C': 15, 'D': 20}
for k in sorted(d.keys() & e.keys()):
print(d[k], k, e[k])
The & ensures that we only use the keys present in both d and e.
Note that we need the sorted call to ensure that the dicts are indexed alphabetically in the situation where the dict keys aren't alphabetically inserted in the first place.
d= {'A': 1, 'B': 5, 'C': 3, 'D': 7}
e= {'A': 18, 'B': 14, 'C': 15, 'D': 20}
for i in d.keys():
print(d[i],i,e[i])
As the key in both dictionaries are same, so if you access one key you can easily access values from both the dictionaries and can print it in any order/format.
d= {'A': 1, 'B': 5, 'C': 3, 'D': 7}
e= {'A': 18, 'B': 14, 'C': 15, 'D': 20}
final_dictionary = {x: d.get(x, 0) + e.get(x, 0)
for x in set(d).union(e)}
print("final dictionary", str(final_dictionary))
I am trying to create a dictionary from a DataFrame where the key sometimes has multiple values.
For example:
df
ID value
A 10
B 45
C 20
C 30
D 20
E 10
E 70
E 110
F 20
And I want the dictionary to look like:
dic = {'A': 10,
'B': 45,
'C':[20,30],
'D': 20,
'E': [10,70,110],
'F': 20}
I tried using the following code:
dic=df.set_index('ID').T.to_dict('list')
But it returned a dictionary with only one value per ID:
{'A': 10,
'B': 45,
'C': 30,
'D': 20,
'E': 110,
'F': 20}
I'm assuming the right way to go about it is with some kind of loop appending to an empty dictionary but I'm not sure what the proper syntax would be.
My actual DataFrame is much longer than this, so what would I use to convert the DataFrame to the dictionary?
Thanks!
example dataframe:
df = pd.DataFrame({'ID':['A', 'B', 'B'], 'value': [1,2,3]})
df_tmp = df.groupby('ID')['value'].apply(list).reset_index()
dict(zip(df_tmp['ID'], df_tmp['value']))
outputs
{'A': [1], 'B': [2, 3]}
Example:
[{"a":{"x":13, "y":32, "z":33}, "b":5, "c":7, "d":8, "e":9}, {"a":{"x":18, "y":28, "z":38}, "b":57, "c":77, "d":87, "e":97}, {"a":{"x":17, "y":72, "z":73}, "b":58, "c":70, "d":80, "e":90}, ...]
This is just a small sample set, but what I would like is a list with a filtered list of items in each dictionary such as below:
Sample Output:
[{"x":13, "b":5, "e"9}, {"x":18, "b":57, "e"97}, {"x":17, "b":58, "e"90}, ...]
I can filter it down to the following:
[{"a":{"x":13, "y":32, "z":33}, "b":5, "e":9}, {"a":{"x":18, "y":28, "z":38}, "b":57, "e":97}, {"a":{"x":17, "y":72, "z":73}, "b":58, "e":90}, ...]
using the following code
for i in range(len(results)):
desired_keys = ['a', 'b', 'e']
bigdict = all_results[i]
filtered = {x: bigdict[x] for x in desired_keys if x in bigdict}
but have yet to be able to figure out how to get the one element of the nested dictionary out.
You cannot just use your approach since it only works for top-level keys. You will need to specify each key and how to access it from the nested dictionary:
>>> [{'x': e['a']['x'], 'b': e['b'], 'e': e['e']} for e in results]
[{'x': 13, 'b': 5, 'e': 9}, {'x': 18, 'b': 57, 'e': 97}, {'x': 17, 'b': 58, 'e': 90}, ...]
As mentioned, all the items in the nested dictionaries must be visited.
This recursive approach
vals = [{"a":{"x":13, "y":32, "z":33}, "b":5, "c":7, "d":8, "e":9}, {"a":{"x":18, "y":28, "z":38}, "b":57, "c":77, "d":87, "e":97}, {"a":{"x":17, "y":72, "z":73}, "b":58, "c":70, "d":80, "e":90}]
def get_items(d, keys):
res = dict()
for k, v in d.items():
if isinstance(v, dict):
res.update(get_items(v, keys))
elif k in keys:
res[k] = v
return res
r = [get_items(d, {'x','b', 'e'}) for d in vals]
print(r)
produces
[{'x': 13, 'b': 5, 'e': 9}, {'x': 18, 'b': 57, 'e': 97}, {'x': 17, 'b': 58, 'e': 90}]
Note: make sure the keys do not appear more than once in any given path along the nested dictionaries.
Another possible recursive approach with a generator function:
def get_vals(d, to_find):
for a, b in d.items():
if a in to_find:
yield (a, b)
yield from [] if not isinstance(b, dict) else get_vals(b, to_find)
data = [{"a":{"x":13, "y":32, "z":33}, "b":5, "c":7, "d":8, "e":9}, {"a":{"x":18, "y":28, "z":38}, "b":57, "c":77, "d":87, "e":97}, {"a":{"x":17, "y":72, "z":73}, "b":58, "c":70, "d":80, "e":90}]
result = [dict(get_vals(i, ['x', 'b', 'e'])) for i in data]
Output:
[{'x': 13, 'b': 5, 'e': 9}, {'x': 18, 'b': 57, 'e': 97}, {'x': 17, 'b': 58, 'e': 90}]
I have a list of dictionaries like this example:
example:
a = [{'C': 3742, 'A': 38799, 'F': 66, 'D': 848, 'B': 12953, 'E': 140}, {'C': 2319, 'A': 23551, 'F': 33, 'D': 568, 'B': 8192, 'E': 87}]
for every single dictionary in the list I would like to sort the items based on the the Keys from A to F. and then make a list of lists (of the sorted dictionary) but only from the values of dictionary. here is the expected output:
expected output:
res = [[38799, 12953, 3742, 848, 140, 66], [23551, 8192, 2319, 568, 87, 33]]
to do so I made the following code in python:
res = []
for i in range(len(a)):
for e in sorted(a[i].keys()):
res.append(a[i][e])
but it does not return what I want. do you know how to fix it?
You want to put the result of from the dictionaries to an array, before adding to the final results
a = [{'C': 3742, 'A': 38799, 'F': 66, 'D': 848, 'B': 12953, 'E': 140}, {'C': 2319, 'A': 23551, 'F': 33, 'D': 568, 'B': 8192, 'E': 87}]
res = []
for i in range(len(a)):
sub_res = []
for e in sorted(a[i].keys()):
sub_res.append(a[i][e])
res.append(sub_res)
A shorter version of this would be:
res = [ [i[e] for e in sorted(i.keys())] for i in a ]
Use List comprehension. Avoid using loops.
y = [[i[key]for key in sorted(i.keys())] for i in x]
To sort items you can use built-in function sorted():
a = [{'C': 3742, 'A': 38799, 'F': 66, 'D': 848, 'B': 12953, 'E': 140}, {'C': 2319, 'A': 23551, 'F': 33, 'D': 568, 'B': 8192, 'E': 87}]
b = [[i[k] for k in sorted(i)] for i in a]
Add a list instead of adding individual elements in res list.
res = []
for i in range(len(a)):
temp = []
for e in sorted(a[i].keys()):
temp.append(a[i][e])
res.append(temp)
Here is another method using the function items of dict:
>>> [[i[1] for i in sorted(e.items())] for e in a]
[[38799, 12953, 3742, 848, 140, 66], [23551, 8192, 2319, 568, 87, 33]]
>>>
It sorts the values by keys.