Get the max of a nested dictionary

Get the max of a nested dictionary

Content Index :

Get the max of a nested dictionary
Tag : python , By : brennen
Date : November 28 2020, 12:01 PM

will help you you can use max with a custom key function, to choose the max genre based on the value of the tuple mapped by it.
try this:
d = {'1111': {'animated': (1, 5.0),'romance':(1, 4.0),'superhero':(1,3.0)},
     '2222': {'genreone': (1, 3.5),'genretwo':(1, 4.8),'superhero':(1,4.0)}}

result = [{"id":key, "genre":max(inner.keys(), key=lambda k:inner[k][1])} for key,inner in d.items()]

[{'id': '1111', 'genre': 'animated'}, {'id': '2222', 'genre': 'genretwo'}]

No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

C# Sum of Values in a nested dictionary where value is a class Dictionary<string, Dictionary<Int16, CommonData>

Tag : chash , By : demize95
Date : March 29 2020, 07:55 AM
I hope this helps . You didn't give some example input/output but I think your looking for something like
var result = yourMainDict.OrderBy(x => x.Value.Sum(v => v.Value.Delivered + v.Value.Submitted + v.Value.Failed));

Create dataframe from nested dictionary keeping nested dictionary as column

Tag : python , By : Chris Hanley
Date : March 29 2020, 07:55 AM
this will help That's not the greatest input data, but if you're confident that the structure of the dictionary won't change, you could try something like the below:
        [x[0] for x in nested_dict.keys()],
        [x[1] for x in nested_dict.keys()],
        [x for x in nested_dict.values()],
    0           1   2
0   timestamp4  324 {326: 3}
1   timestamp3  323 {325: 2}
2   timestamp   321 {321: 0}
3   timestamp2  322 {323: 1}

How can I create a flat dictionary from a nested dictionary whose keys are a subset of a reference dictionary?

Tag : python , By : hyperNURb
Date : March 29 2020, 07:55 AM
around this issue Using a generator, this is fairly straight forward:
def make_flat_tuples(data, ref):
    for k, v in data.items():
        if isinstance(v, dict):
            for x in make_flat_tuples(v, ref[k]):
                yield x
            yield ref[k], v

flat = dict(make_flat_tuples(nested, reference))
from collections import defaultdict

reference = defaultdict(dict)
reference['agent'] = defaultdict(dict)

reference['agent']['address'] = 'agentaddress'
reference['agent']['zone']['id'] = 'agentzoneid'
reference['eventid'] = 'eventid'
reference['file']['hash'] = 'filehash'
reference['file']['name'] = 'filename'

nested = defaultdict(dict)

nested['agent']['address'] = ''
nested['eventid'] = '1234566778'
nested['file']['name'] = 'reallybadfile.exe'

print(dict(make_flat_tuples(nested, reference)))
    'agentaddress': '', 
    'eventid': '1234566778', 
    'filename': 'reallybadfile.exe'

update nested dictionary values from another nested dictionary based on mapping already provided in the dictionary

Tag : python , By : Santhanam
Date : March 29 2020, 07:55 AM
this one helps. In your function find_input_value you are not propagating the output through the recursions properly. Recursive functions need to have consistent return values. You have 2 returns that send a result and 1 that sends a None. Here is a version that works for me, even though I suspect it can be simplified.
def find_input_value(k,input_json):  
  if k in input_json:
    val = input_json[k]
  for v in input_json.values():
    if 'val' in locals(): #check if val has been defined
      if val is not None: #needs to be defined and not None
        break             # kill the loop cause found it
    if isinstance(v, dict):
      val = find_input_value(k,v)
  return val if 'val' in locals() else None # if input_json is not dict return None

question regarding a nested dictionary is there a way to merge a nested dictionary in one dictionary

Tag : python , By : Xander
Date : March 29 2020, 07:55 AM
With these it helps I'm following a python course on runestone and i'm stuck with the following question: , This should do it:
pokemon_total = {}

for player, dictionary in pokemon_go_data.items():
    for pokemon, candy_count in dictionary.items():
        if pokemon in pokemon_total.keys():
            pokemon_total[pokemon] += candy_count
            pokemon_total[pokemon] = candy_count

most_common_pokemon = max(pokemon_total, key=pokemon_total.get)

Related Posts Related QUESTIONS :
  • How to click on item in navigation bar on top of page using selenium python?
  • Add multiple EntityRuler with spaCy (ValueError: 'entity_ruler' already exists in pipeline)
  • error when replacing missing ')' using negative look ahead regex in python
  • Is there a way to remove specific strings from indexes using a for loop?
  • select multiple tags by position in beautifulSoup
  • pytest: getting AttributeError: 'CaptureFixture' object has no attribute 'readouterror' capturing stdout
  • Shipping PyGObject/GTK+ app on Windows with MingW
  • Python script to deduplicate lines in multiple files
  • How to prevent window and widgets in a pyqt5 application from changing size when the visibility of one widget is altered
  • How to draw stacked bar plot from df.groupby('feature')['label'].value_counts()
  • Python subprocess doesn't work without sleep
  • How can I adjust 'the time' in python with module Re
  • Join original np array with resulting np array in a form of dictionary? multidimensional array? etc?
  • Forcing labels on histograms in each individual graph in a figure
  • For an infinite dataset, is the data used in each epoch the same?
  • Is there a more efficent way to extend a string?
  • How to calculate each single element of a numpy array based on conditions
  • How do I change the width of Jupyter notebook's cell's left part?
  • Measure distance between lat/lon coordinates and utm coordinates
  • Installing megam for NLTK on Windows
  • filter dataframe on each value of a samn column have a specific value of another column in Panda\Python
  • Threading with pubsub throwing AssertionError: 'callableObj is not callable' in wxPython
  • Get grouped data from 2 dataframes with condition
  • How can I import all of sklearns regressors
  • How to take all elements except the first k
  • Whats wrong with my iteration list of lists from csv
  • Tensorflow Estimator API save image summary in eval mode
  • How to Pack with PyQt - how to make QFrame/Layout adapt to content
  • How do I get certain Time Range in Python
  • python doubly linked list - insertAfter node
  • Open .h5 file in Python
  • Joining a directory name with a binary file name
  • python, sort list with two arguments in compare function
  • Is it possible to print from Python using non-ANSI colors?
  • Pandas concat historical data using date minus some number of days
  • CV2: Import Error in Python OpenCV
  • Is it possible to do this loop in a one-liner?
  • invalid literal for int() with base 10: - django
  • Why does my code print a value that I have not assigned as yet?
  • the collatz func in automate boring stuff with python
  • How to find all possible combinations of parameters and funtions
  • about backpropagation deep neural network in tensorflow
  • Sort strings in pandas
  • How do access my flask app hosted in docker?
  • Replace the sentence include some text with Python regex
  • Counting the most common element in a 2D List in Python
  • logout a user from the system using a function in python
  • mp4 metadata not found but exists
  • Django: QuerySet with ExpressionWrapper
  • Pandas string search in list of dicts
  • Decryption from RSA encrypted string from sqlite is not the same
  • need of maximum value in int
  • a list of several tuples, how to extract the same of the first two elements in the small tuple in the large tuple
  • Display image of 2D Sinewaves in 3D
  • how to prevent a for loop from overwriting a dictionary?
  • How To Fix: RuntimeError: size mismatch in pyTorch
  • Concatenating two Pandas DataFrames while maintaining index order
  • Why does this not run into an infinite loop?
  • Python Multithreading no current event loop
  • Element Tree - Seaching for specific element value without looping
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com