How flatten semi nested python dictionary [duplicate] - python

This question already has answers here:
Flatten nested dictionaries, compressing keys
(32 answers)
Closed 3 years ago.
I have a python dictionary like following:
score_dictionary={'Agriculture':89,'Health':{'Public':90,'Private':78},'Mines':70,'Commerce':67}
Using this dictionary, I want to convert to the following:
score_dictionary={'Agriculture':89,'Health_public':90,'Health_Private':78,'Mines':70,'Commerce':67}
Now I'm stuck at how to convert it?

You could use isinstance to check whether or not the value in a given key/value pair consist in another dictionary, format the key name with string formatting and update accordingly:
d = {}
for k,v in score_dictionary.items():
if not isinstance(v, dict):
d[k] = v
else:
for k_, v_ in v.items():
d[f'{k}_{k_}'] = v_
print(d)
{'Agriculture': 89,
'Health_Public': 90,
'Health_Private': 78,
'Mines': 70,
'Commerce': 67}

Related

python dictionaries values and keys [duplicate]

This question already has answers here:
How to filter a dictionary according to an arbitrary condition function?
(7 answers)
Closed 4 years ago.
I've got dictionary called humans. I want to loop through that dictionary and if value is less than 20 print dictionary key.
humans = {"Danny": 33, "Jenny": 22, "Jackie": 12, "Ashley": 33}
Your description of the problem is almost a perfect pseudo-code for how you would implement that:
# I've got dictionary called humans.
humans = {"Danny": 33, "Jenny": 22, "Jackie": 12, "Ashley": 33}
for key, value in humans.items(): # I want to loop through that dictionary
if value < 20: # and if value is less than 20
print(key) # print dictionary key.
Try this:
for k, v in humans.items():
if v > 20:
print(k)
Or, a more pythonic way:
print([k for k, v in humans.items() if v > 20])
Try this, using generator expressions:
result = (k for k, v in humans.items() if v > 20)
print(', '.join(result))
I used commas as separators, if you need each item in a different line simply substitute ', ' with '\n'.
Loop over items().
You can use comprehension (no need to use [ ] as it is in parenthesis already):
print(k for k,v in humans.items() if v > 20)
or really loop:
for k,v in humans.items():
if v > 20:
print(k)

how to iterate through json key,values in multiple dictionaries in python [duplicate]

This question already has answers here:
Finding matching keys in two large dictionaries and doing it fast
(11 answers)
Find common keys of a number of dictionaries
(5 answers)
Closed 4 years ago.
i am trying to compare keys of different dictionaries stored in json.if keys are same then store those keys in another dictionary but i am not getting the required output. input looks like:
[
{
"huma":10,
"sana":25
},
{
"sara":12,
"huma":20,
" zeb:15
}
]
what i tried is:
def compare():
result_dictionary = {}
with open('data.json') as data_file:
data = json.load(data_file)
for d1 in data:
for key, value in d1.items():
print("key: {key} | value: {value}".format(key=key, value=value))
compare()
i am confused how to compare these keys of multiple dictionaries and key which matches store them in a new dictionary? the output should be "Huma"because only that is equal in both dictionaries.
Using collections
Demo:
import collections
d = [{ "huma":10,"sana":25}, { "sara":12,"huma":20,"zeb":15}]
dd = collections.defaultdict(list)
for i in d:
for k,v in i.items():
dd[k].append(v)
print([k for k,v in dd.items() if len(v) > 1])
Output:
['huma']

Dictionary changing key value Python [duplicate]

This question already has answers here:
Change the name of a key in dictionary
(23 answers)
Closed 6 years ago.
I have got a dictionary in the form of:
{0.1: (0.7298579,0.7987254)}
which corresponds to: {test_size: (train_error, test_error)}.
I would like to change the key value test_size into 1 - test_size. So that we obtain:
{0.9: (0.7298579, 0.7987254)}
How can I do this?
You can do this :
>>> d = {0.1:(0.7298579,0.7987254)}
>>> new_d = {1-k: v for k, v in d.items()}
>>> new_d
{0.9: (0.7298579, 0.7987254)}
If the dict is not horribly huge, you can just create a new dict and copy the old one with new keys.

How do you return a new dictionary that only contains a certain type? [duplicate]

This question already has answers here:
How do I filter out non-string keys in a dictionary in Python?
(5 answers)
Closed 7 years ago.
How can I specify a new dictionary to only append certain types. For example if my old list was {'hello': 1, 2:3, 3.0:'hi'}, how could I make my new list check for the type and then only append that type in it. So new_dict[int] = {2:3} or new_dict[str] = {'hello': 1}?
How about this
d = {'hello': 1, 2:3, 3.0:'hi'}
final_d = {k: v for k, v in d.items() if isinstance(v, int) and isinstance(k,int)}

Sorting by value in a python dictionary? [duplicate]

This question already has answers here:
How do I sort a dictionary by value?
(34 answers)
Closed 8 years ago.
I have an assignment in which a series of items and the amount a store carries of that item is given which I then have to put into a dictionary and display with the highest amount of stock to the lowest amount of stock.
The dictionary looks a bit like this:
items = {'socks': 10, 'hammers': 33, 'keyboards': 56}
and the output would look like this:
keyboards: 56
hammers: 33
socks: 10
After getting the dictionary set up, I'm having difficulty with the second part... does anyone know how I could sort by value?
It's easy to make a sorted list of (key, value) pairs:
import operator
slop = sorted(thelist.items(), key=operator.itemgetter(1), reverse=True)
and then you can loop over it to display it, e.g in Python 2:
for k, v in slop:
print '{}: {}'.format(k, v),
print
To sort you can use sorted method:
items = {'socks': 10, 'hammers': 33, 'keyboards': 56}
sorted_items = sorted(items.items(), key=lambda v: v[1], reverse = True)
As a key you specify to sort by value in the items dict. And to print it, you can just use:
for k,v in sorted_items:
print("{}:{}".format(k,v))

Categories

Resources