create new dictionary from mapping list into dictionary - python

I want to create new dictionary by mapping list into dictionary, so the list item will be the key and the dictionary will be the value.
Students List :
[Student1,Student2,Student3]
dictionary:
{Math:90, CS:94, Since:89}
the expected result is one dictionary:
{
"Student1":{
Math:90
},
"Student2":{
CS:94
},
"Student3":{
Since:89
}
}
I tray this:
new_dic=dic()
new_dic = dic(zip(students,dic1)
output:
{
Student1:Math,
Student2:CS,
Student3:Since
}
but it give me unexpected result. also I try the solution here and it didn't works for me.

Use zip along with some modification to reproduce the inner dict structure
names = ["Student1", "Student2", "Student3"]
values = {"Math": 90, "CS": 94, "Since": 89}
result = {name: {course: val} for name, (course, val) in zip(names, values.items())}

Alternatively, you could use:
a = ['student1','student2','student3']
b = { "Math":90 , "CS":94, "Since":89 }
c = {k1: {k2: v} for (k1,k2,v) in zip(a, b.keys(), b.values())}

Related

Group similar list elements into dict without grouping it's multiple occurence

I have a huge list where I convert it to a dict(based on 1st list element) for quick search with key.
List:
[0100,A,1.00,1]
.
.
[0450,A,1.00,1]
[0470,B,1.00,1]
[0480,A,1.00,1]
[0490,A,1.00,1]
[0500,A,1.00,1] #list-1 for below ref
[0510,B,1.00,1]
[0520,A,1.00,1]
[0530,A,1.00,1]
[0500,A,1.00,1] #list-2 for below ref
[0510,B,1.00,1]
[0520,X,1.00,1] #........
Converting into Dic:
for key, *vals in bytes_data: #Probably need a diff approach here itself instead appending
data_dict.setdefault(key, []).append(vals)
Dict looks like
{
'0450': [[A,1.00,1]],
'0470': [[B,1.00,1]],
'0480': [[A,1.00,1]], #......
}
Now, my current scenario needs to chunk data like 4xx/5xx/... based on situations.
For which, I use..
key_series = ["0" + str(x) for x in range(500, 600, 10)]
article_data = {
key: data_dict[key] for key in set(key_series) & set(data_dict)
}
The issue is, for some series like 5xx there are multiple occurrences. In that case My dict is grouped like
{
0500: [list-1,list-2,..],
0510: [list-1,list-2,..]
}
But, I need something like
{
0500-1: {0500: [list-1], 0510: [list-1],....},
0500-2: {0500: [list-2], 0510: [list-2],....},
}
Any trick to achieve this ? Thanks.
Not sure, if this is what you want, letme know if this solves your problem
from collections import defaultdict
data_dict = {
"0500": [["A",1.00,1]],
"0510": [["A",1.00,1], ["B",1.00,1], ["B",1.00,1]],
"0520": [["A",1.00,1], ["D",1.00,1]]
}
key_series = ["0" + str(x) for x in range(500, 600, 10)]
article_data = {
key: data_dict[key] for key in set(key_series) & set(data_dict)
}
res = defaultdict(dict)
for k ,v in data_dict.items():
for i, d in enumerate(v):
# for now 0500 is hardcoded, which can be made dynamic as per requirement
res[f"0500-{i+1}"][k] = d
print(res)

How to sort nested dictionary by values in python

PROBLEM
I have a dictionary and it is nested i want to sort it using vlaues. There are many solution out there for the same question but I couldnt find one solution that satisfies my sorting condition
CONDITION
I want to sort thee dict in descending order of the given likes in the dict
Dict
dict = {actor_name: {movie_name: likes}
eg:- {'gal gadot': {'red notice': 1000}, 'tom holland': {'spiderman-nwh': 3000}}
output should be:- {'tom holland': {'spiderman-nwh': 3000}, 'gal gadot': {'red notice': 1000}}
I suggest improving your data structure first.
As an example you could use a list of dictionaries list[dict].
This would help you later, if you expand your structure.
Try this structure:
data = [
{
"actor": "gal gadot",
"movies": {
"name": "red notice",
"likes": 1000,
},
},
{
"actor": "tom holland",
"movies": {
"name": "spiderman-nwh",
"likes": 3000,
},
},
]
Using that structure, you can sort your data like this:
# Least likes first
least_likes_sorted = = sorted(data, key=lambda x: x["movies"]["likes"])
# Most likes first
most_likes_sorted = sorted(data, key=lambda x: x["movies"]["likes"], reverse=True)
You could build a list of tuples where each element is (likes, movie, actor).
Then sort the list in reverse.
Then reconstruct your dictionary.
Like this:
data = {'gal gadot': {'red notice': 1000}, 'tom holland': {'spiderman-nwh': 3000}}
lot = []
for k, v in data.items():
k_, v_ = next(iter(v.items()))
lot.append((v_, k_, k))
newdata = {a : {b: c} for c, b, a in sorted(lot, reverse=True)}
print(newdata)
Output:
{'tom holland': {'spiderman-nwh': 3000}, 'gal gadot': {'red notice': 1000}}

How to get flattened list of all inner level nested keys in dictionary - python?

I'm trying to get a list of all keys in the nested level of my dictionary.
My dictionary resembles:
my_dict= {
'DICT':{
'level_1a':{
'level_2a':{}
},
'level_1b': {
'level_2b':{},
'level_2c':{}
}
}
My desired output should resemble:
['level_2a', 'level_2b', 'level_2c']
What I've tried:
[list(v) for k, v in json['DICT'].items()]
My current output:
[['level_2a'], ['level_2b', 'level_2c']]
I want my result to be fully flattened to a single-level list. I've tried flattening libraries but the result tends to appear as: ['level_2a', 'level_2blevel_2c'] which is incorrect. Not looking to make the code more complex by creating another method just to flatten this list.
Would appreciate some help, thank you!
Try:
my_dict = {
"DICT": {
"level_1a": {"level_2a": {}},
"level_1b": {"level_2b": {}, "level_2c": {}},
}
}
lst = [vv for v in my_dict["DICT"].values() for vv in v]
print(lst)
Prints:
['level_2a', 'level_2b', 'level_2c']

Python - Pull Out Values from Only Dictionaries that Meet a Certain Criteria

I have a Python list called "results" that has dictionaries as its values:
results = [
{
'postingStatus': 'Active',
'postEndDate': '1601683199000',
'boardId': '_internal',
'postStartDate': '1591084714000)'
},
{
'postingStatus': 'Expired',
'postEndDate': '1601683199000',
'boardId': '_external',
'postStartDate': '1591084719000)'
}
]
How would I create a list that gets all the values from the dictionary where the 'boardID' value is '_internal' (but ignores the dictionary where 'boardID' is '_external')? As an end result, I'm hoping for a list with the following contents:
['Active','1601683199000','_internal','1591084714000']
You can use list-comprehension:
out = [v for d in results for v in d.values() if d["boardId"] == "_internal"]
print(out)
Prints:
['Active', '1601683199000', '_internal', '1591084714000)']
without using List-comprehension
for items in results:
if items['boardId'] == '_internal':
lst1 = list(items.values())
print(lst1)

How to remove empty or None fields in deeply nested dictionary of unknown depth?

I have a dictionary of deeply nested dictionaries and I am trying to remove all k-v pairs that are None or "". The below dictionary d is an example of the input.
d = {
"1": {
"1_1": 'a real value',
"1_2": ""
},
"2": None,
"3": {
"3_1": {
"3_2": None
}
}
}
Normally, to remove empty fields in a dictionary, the command {k:v for k,v in d.items() if v} does the job. But in this case, I want to remove all the nested dictionaries whose values are empty or null, and I can't figure out how to do this. Any ideas?
After d passes through this transformation, all the empty dictionaries whose values are empty should be gone. It should look like this:
{
"1": {
"1_1": 'a real value',
}
}
You can write a function to recursively remove empty dictionaries. For example:
def return_non_empty(my_dict):
temp_dict = {}
for k, v in my_dict.items():
if v:
if isinstance(v, dict):
return_dict = return_non_empty(v)
if return_dict:
temp_dict[k] = return_dict
else:
temp_dict[k] = v
return temp_dict
For example, if d is:
d = {
"1": {
"1_1": 'a real value',
"1_2": ""
},
"2": None,
"3": {
"3_1": {
"3_2": None
}
}
}
then my custom function return_non_empty will return:
>>> return_non_empty(d)
{'1': {'1_1': 'a real value'}}
You can use recursion with a dictionary comprehension:
d = {'1': {'1_1': 'a real value', '1_2': ''}, '2': None, '3': {'3_1': {'3_2': None}}}
def get_d(d):
return {a:c for a, b in d.items() if (c:=(b if not isinstance(b, dict) else get_d(b)))}
print(get_d(d))
Output:
{'1': {'1_1': 'a real value'}}
Note: this solution uses Python's assignment expressions (:=) available in versions >= 3.8. For a solution that does not use this paradigm, please see #Anonymous's answer.
This python function recursively removes dictionary keys whose values are empty, None, False, or 0.
def remove_empty_keys(dictionary):
if isinstance(dictionary, dict):
for key, value in dictionary.copy().items():
if isinstance(value, dict):
remove_empty_keys(value)
if not value:
del(dictionary[key])
Similar to #Ajax1234's answer but this function acts directly on target dictionary rather than outputting a new one.

Categories

Resources