logo
Tags down

shadow

How do you sort a dictionary by value?


By : Tommy
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further I often have to sort a dictionary, consisting of keys & values, by value. For example, I have a hash of words and respective frequencies, that I want to order by frequency. , Use:
code :
using System.Linq.Enumerable;
...
List<KeyValuePair<string, string>> myList = aDictionary.ToList();

myList.Sort(
    delegate(KeyValuePair<string, string> pair1,
    KeyValuePair<string, string> pair2)
    {
        return pair1.Value.CompareTo(pair2.Value);
    }
);
var myList = aDictionary.ToList();

myList.Sort((pair1,pair2) => pair1.Value.CompareTo(pair2.Value));


Share : facebook icon twitter icon

Sort list dict by key of dictionary inside a dictionary in Python


By : kevin makwana
Date : March 29 2020, 07:55 AM
I wish this help you Is that a bubblesort? Really?
Anyway, there's no need to write your own sort function:
code :
raw_sizes.sort(key=lambda d: d['selections']['size'])

Can't seem to iterate over a sorted dictionary where the keys are number strings. How do you sort a dictionary to iterat


By : Mars
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further dict.iteritems() returns 2-tuples, which cannot be converted into ints.
code :
for j in sorted(dic, key=int):
    print dic[j]

Sort a list of key, values where value is dictionary AND sorting needs to be done on STRING value in the dictionary


By : fomas
Date : March 29 2020, 07:55 AM
will be helpful for those in need your input data is not a dictionary but a list of tuples. Each tuple second element is the dictionary you want to use to sort with a given value.
code :
sorted_team_map = sorted(team_map, key=lambda x : x[1]['team_name'])

In python, I want to sort a dictionary based on the dictionary of dictionary values


By : Siobhan Burke
Date : March 29 2020, 07:55 AM
help you fix your problem In python I have a dictionary of dictionary such as , You can use a custom key for sorting:
code :
print(dict(sorted(my_dict.items(), key=lambda x: x[1]['mark3'], reverse=True)))
{'C': {'mark1': '11', 'mark2': '19', 'mark3': '25'}, 'A': {'mark1': '15', 'mark2': '12', 'mark3': '20'}, 'B': {'mark1': '10', 'mark2': '90', 'mark3': '14'}}
from collections import OrderedDict
my_dict = OrderedDict([('A', {'mark1': '15', 'mark2': '12', 'mark3': '20'}), ('B', {'mark1': '10', 'mark2': '90', 'mark3': '14'}), ('C', {'mark1': '11', 'mark2': '19', 'mark3': '25'})])
print(OrderedDict(sorted(my_dict.items(), key=lambda x: x[1]['mark3'], reverse=True)))
print(dict(sorted(my_dict.items(), key=lambda x: (x[1]['mark3'], x[1]['mark2']), reverse=True)))

Sort based Dictionary of Dictionary of Dictionary Values?


By : mkmkia
Date : March 29 2020, 07:55 AM
like below fixes the issue The following code will sort any dictionary by its key and recursively sort any dictionary value that is also a dictionary by its key and makes no assumption as to the content of the dictionary being sorted. It uses an OrderedDict but if you can be sure it will always run on Python 3.6 or greater, a simple change can be made to use a dict.
code :
from collections import OrderedDict

d = {
    'Benefits': {
        1: {
            'BEN1': {
                'D': [{'description': 'D1'}],
                'C': [{'description': 'C1'}]
            }
        },
        2: {
            'BEN2': {
                'D': [{'description': 'D2'}],
                'C': [{'description': 'C2'}]
            }
        }
    }
}

def sort_dict(d):
    items = [[k, v] for k, v in sorted(d.items(), key=lambda x: x[0])]
    for item in items:
        if isinstance(item[1], dict):
            item[1] = sort_dict(item[1])
    return OrderedDict(items)
    #return dict(items)

print(sort_dict(d))
Related Posts Related Posts :
  • How to check whether string contains specific string in c#
  • UPnP hole punching can't use external IP to access device on local subnet
  • Is there a way to use a conditional when declaring method variables?
  • c# interop Excel - disable or remove automatic page breaks
  • How can I read in these commands from a file using?
  • Pinch and rotate around a point using MRTK and Hololens 1
  • Enhance performance to paint image, is SIMD perhapse a solution?
  • Which one has better performance, data types .NET or alias name data types C#?
  • HttpClient GetAsync taking ~2 seconds
  • linq fastest where method
  • Why can I read more than 254 characters with Console.ReadLine when the docs suggest that I shouldn't be able to?
  • C# - Delayed execution for a collection of items
  • How to display images in a CollectionView from a Base64 string?
  • Convert class object to class index
  • c# identifier expected in controller
  • Subscribe to multiple Observables and gets notified on the same thread
  • how to create windows service using crud operations in c# asp.net
  • Iterating through list of values in a dictionary c#
  • How to Implement Expo.io Push Notifications Send Through C#
  • Gridview columns not being set to width I enter
  • Impersonate User with Forms Authorization
  • ASP.NET MVC Impersonate not working with Forms Authentication
  • Found a potential bug in Moq library while selecting a constructor
  • I want to show a list but page is empty
  • Can this kind of concurrency problem be solved with async/await?
  • Yield keyword giving unexpected values for IEnumerable
  • Many DLLs in System namespace are included when installing library via Nuget
  • C# - range for textbox inputs
  • the Console.ReadLine() Doesn't set the string as the user input
  • Get notified when a variable changed
  • How to list players in room in Photon?
  • Link compile-time created resources to a class library
  • How to quickly choose numbers and weights in such a way as to obtain a specific weighted sum?
  • Downgrade .Net Core project from 3.1 to 2.2 - The type or namespace name 'IWebHostEnvironment' could not be found
  • c# multiplying array elements using system.numerics
  • Private methods vs local functions
  • C# project wants .NET 4.7.1 but I can't install it
  • Binding to object itself, doesn't update when individual property changes
  • remove duplicate from list in object c#
  • JSON.NET - find JObject by value regex in complex object?
  • Save an unknown sized array from unknown string length
  • Camera not centre on player sprite (monogame)
  • How to set a default type for T in a static generic method?
  • How can I insert multiple items of data into SQL using Web API?
  • Finding longest time in an array
  • How to find two quotation marks in a string
  • X509Certificate2 certification issue
  • Image format change in Azure
  • Why is there such big time difference in searching for element with higher index in ConcurrentBag?
  • Async Lambda Issue
  • C# SSIS Script Task - Add Thousand Seperator when formatting Excel column
  • How to check if a textbox starts with numeric value
  • c# Strange Pairs || I can't spot the difference between these 2 solutions?
  • str.Split(".") not working in C# interactive window but work in C# .Net core project?
  • How to do 3 conditions with if else C#
  • merge two lists of same type in c#
  • Blazor - SortBy parameter for table column component
  • InvalidCastException: Specified cast is not valid Error when tried to fetch image from url
  • Search based on Properties
  • Ref string parameter is empty?
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org