w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Transfor List to Nested Dictionary using linq C#
You can try this with a pair of GroupBy and a pair of calls of ToDictionary, like this: var res = list .GroupBy(v => v.ID) .ToDictionary( g => g.Key , g => g.GroupBy(v => v.START_DATE.Date) .ToDictionary(h => h.Key, h => h.Seelct(x => x.ID_OWNER).Distinct().Count()) ); If you would like to also add the total time per day, you can do this: var res = list .GroupBy(v => v.ID) .ToDictionary( g => g.Key , g => g.GroupBy(v => v.START_DATE.Date) .ToDictionary(h => h.Key, h => new { Count = h.Seelct(x => x.ID_OWNER).Distinct().Count()) , TotalTime = h.Sum(h => x.END_DATE-x.START_DATE) } );

Categories : C#

Nested dictionary in Python
The problem here is that you try to access values in report2 that you haven't created yet. It's pretty much the same problem you'd get with a variable. Imagine you had this code: i = 1 if i == 1: a += 2 else: a = 2 You can't do a += 2 because there is no value there. So to fix this, you need to deal with the case where you're seeing a key for the first time. You can use defaultdict instead of dict, or the setdefault method, or an explicit in check, or a try, but usually one of the first two will be easier.

Categories : Python

Nested Dictionary with RestKit 0.2.0
I've got this working by changing all the properties from 'weak' to 'strong'. First, I activated the logging per your suggestion RKLogConfigureByName("RestKit/ObjectMapping", RKLogLevelTrace); It showed that IAPClientInfo and IAPClientMessage objects were being populated correctly, suggesting there was no issue in the basic set-up. The IAPClientInfo object was being populated correctly but was going null, hence I suspected there was a memory management issue. Reading this article http://www.raywenderlich.com/5677/beginning-arc-in-ios-5-part-1 clarified the desired usage - I need all the properties to 'own' what they point to. Hence, I need them to use 'strong' not 'weak' semantics. I'm using ARC. The 'weak' semantics lead the pointer (I suspect) to point to 'nil' once the 'creati

Categories : IOS

Get to nested dictionary in list
Use a list comprehension: only_last_and_first = [d for d in L if 'firstname' in d and 'lastname' in d] Now you have a list of dictionaries that have those two keys. Demo: >>> L = [{'color':'yellow','fruit':'banana'},{'firstname':'Jack','lastname':'Black'}] >>> [d for d in L if 'firstname' in d and 'lastname' in d] [{'lastname': 'Black', 'firstname': 'Jack'}] If you only wanted the first such a dictionary, use next() and a generator expression: first = next((d for d in L if 'firstname' in d and 'lastname' in d), None) Here first will be set to either the first dictionary with the two keys, or None if there is no such dictionary. If such syntax is a little daunting, here is a version with a for loop instead: first = None for d in L: if 'firstname' in d and '

Categories : Python

How to get below format of nested dictionary?
you can use that: foreach (var item in ObjDict) { if (Dict.ContainsKey(item.Value)) { var e = Dict[item.Value]; e.Add(item.Key); } else { Dict.Add(item.Value, new List<string>() { item.Key }); } }

Categories : C#

c# Nested dictionary of different depths
If you can know your "key structure" in advance, it might just be cheaper to use a Dictionary<string, string> and generate a key that is a concatenation of the 3 parts: "ABC"... Avoids the nest and offers direct lookups. If you know that a = 1, b = 2, and c = 3 for example, you can concatenate them to a string of "123" and that's your key for the Dictionary lookup. This is essentially how HttpContext Caching and .NET 4.0 MemoryCache work as well. EDIT: If you don't always have all 3 values, use string.Format with a key structure that provides a divider/separator between values. This is generally a best practice anyway, otherwise you can have key collisions easily: private const string _keyFormat = "{0}_{1}_{2}"; private string GenerateKey(object a, object b, object c) { retu

Categories : C#

Retrieving branches from a nested dictionary
Probably the best way to do it is a depth first search using memoization to optimize already parsed branch. To do this, the simplest way is to store in each node, all the parent nodes preformatted. For instance the node a would have I have, the node dog would have I have a, etc. This way, you will be able to extract all branches in a O(n) complexity, with n is the nodes count. However this requires a little modification of the structure. For instance class Node(dict): def __init__(self,parent,value,parent_str): self.parent = parent self.value = value self.children = {} parent.children[value] = self self.parent_str = parent_str+' '+value def __repr__(self): return self.parent_str+' '+value def addChild(self,va

Categories : Python

Nested dictionary comprehension python
{inner_k: myfunc(inner_v)} isn't a dictionary comprehension. It's just a dictionary. You're probably looking for something like this instead: data = {outer_k: {inner_k: myfunc(inner_v) for inner_k, inner_v in outer_v.items()} for outer_k, outer_v in outer_dict.items()} For the sake of readability, don't nest dictionary comprehensions and list comprehensions too much.

Categories : Python

How to push into array nested in dictionary?
{"$push": {"homework.bio", 92}}) It should be :, not ,. {'a', 1} is a set of two elements in Python, that's why you get the error.

Categories : Python

Python nested dictionary from pathname
The easy to write recursive function expands to a stack N levels deep, then builds the dictionary from the bottom up as it collapses back up through the stack. That gives a hint on an easy way to do this... Go backwards. path = '1/2/3' toks = [t for t in path.split('/') if t] ret = path for tok in reversed(toks): ret = {tok: ret} return ret

Categories : Python

iterating through a nested dictionary in python
Something like this: import os from collections import Counter,defaultdict d2 = defaultdict(dict) word_list = ['vs', 'mln', 'money'] for fil in d.values(): with open(fil[0]) as f: path, name = os.path.split(fil[0]) words_c = Counter([word for line in f for word in line.split()]) for word in word_list: d2[word][name] = words_c[word] Now access d2 as: d2['vs']['5.txt']

Categories : Python

Check nested dictionary values in python
Use .get() with empty dictionaries as defaults: if 'Dict4' in Dict1.get('Dict2', {}).get('Dict3', {}): print "Yes" If the Dict2 key is not present, an empty dictionary is returned, so the next chained .get() will also not find Dict3 and return an empty dictionary in turn. The in test then returns False. The alternative is to just catch the KeyError: try: if 'Dict4' in Dict1['Dict2']['Dict3']: print "Yes" except KeyError: print "Definitely no"

Categories : Python

finding sum of values in a nested dictionary in python
with open(f) as fil assigns fil to whatever the contents of f are. When you later access the entries in your dictionary as total=sum(math.log(prob)*d2[fil][word].values()) I believe you mean total = sum(math.log(prob)*d2[f][word]) though, this doesn't seem to quite match up with the order you were expecting, so I would instead suggest something more like this: word_list = [#list of words] file_list = [#list of files] dictionary = {#your dictionary} summation = lambda file_name,prob: sum([(math.log(prob)*dictionary[word][file_name]) for word in word_list]) return_value = [] for file_name in file_list: prob = #something return_value.append(summation(file_name)) The summation line there is defining an anonymous function within python. These are called lambda functions. Essent

Categories : Python

Associating string keys with int in nested dictionary
You are missing a few parts. First of all, you need to pass any conversion that you have already determined (e.g. A = 1) to your function when you call it recursively - otherwise you won't use the same replacement for the same key in the nested dictionaries. Also, you need some way to ensure that when you generate a new key, that key is used up and won't be used again. When you increment count in your function, this will only affect it within the current call to the function - any calls higher up the chain will keep using a lower count, and so keys will be used multiple times. My attempt: import itertools def transform(d, key_generator=None, conversion=None): if key_generator is None: key_generator = itertools.count(start=1) if conversion is None: conversion = {}

Categories : Python

Extract nested dictionary values in Python
The problem is with your Dictout[key] = value in Python Dictionary the keys are unique Assume _d = {1: 'one', 2: 'two'} >>> print _d {1: 'one', 2: 'two'} >>> _d[1] = 'another one' >>> print _d {1: 'another one', 2: 'two'} I guess in your for loop you are overwriting value of an existing key, that's why only your last entry is getting stored !. Try changing your data structure, something like list of dictionaries, so that your output may look like, my_out_list = [{1: 'one', 2: 'two'}, {1: 'another one', 2: 'two'}]

Categories : Python

Dictionary with Multiple Values from a Nested List
This is a case for collections.defaultdict: import collections my_list = [('key1', 'topic1', 'content1'), ('key2', 'topic1', 'content2'), ('key3', 'topic2', 'content3')] my_dict = collections.defaultdict(list) for _, key, value in my_list: my_dict[key].append(value) print(my_dict) Gives us: defaultdict(<class 'list'>, {'topic2': ['content3'], 'topic1': ['content1', 'content2']}) The defaultdict creates the list for the values if it doesn't exist, meaning we can do this really easily by just looping over the list and appending the values to the key. It acts exactly as a normal dictionary in every other way, but if you need a normal dict, you can just use dict() on it.

Categories : Python

Why does a small pickled nested dictionary use a lot of memory?
You might consider giving objgraph a try: it allows you to inspect what's going on in your program's memory; it can generate visual output too. See http://mg.pov.lt/objgraph/ for more information.

Categories : Python

Access and setting nested dictionary values
Assuming you want to continue down this path, rather than using the configurationmanager already built into .NET, or an existing ini-file wrapper as already mentioned in comments, you need to do this to add values to your in-memory structure: When you've got a section, you need to add it. iniSettings.Add(section, new Dictionary<string, string>()); When you've got a section (after adding it), a key and a value, you need to add that. iniSettings[section].Add(key, value); This will lead to a structure that resembles + section1 + key1, value + key2, value + section2 + key1, value etc. You can check if a section exists in your in-memory structure by calling bool sectionExists = iniSettings.ContainsKey(section); which will return a bool. The same goes for keys, of cou

Categories : C#

How do I read a nested dictionary in a Django template?
This is a generator function that will return each row in a loop: def next_row(data): for day,rooms in data.iteritems(): for room,times in rooms.iteritems(): for time in times: yield (day, room, time) Use it like this: for row in next_row(data): # do something with row

Categories : Python

How to access a nested Dictionary<> objects in a foreach loop
That's because the value of the string key is not a list. Change the declaration of the Dictionary to Dictionary<string, List<Dictionary<string, string>>> dict; if that's what you want. Or you could just grab the dictionary inside the first foreach loop like this: Dictionary<string, string> val = dict[key]; and use it from there. But either way, you're trying to iterate against something that's not enumerable. I think you may have the Dictionary defined like you want -you just don't need an inner loop.

Categories : C#

Turning a flat Python tuple into a nested dictionary?
For each 2-tuple, split the first tuple [el.strip() for el in path.split('|')], then follow that path creating dictionaries and sub-dictionaries. I'll edit in some code within a few minutes. d = {'count': 0, 'children': {}} for (path, count) in els: path = [el.strip() for el in path.split('|')] here = d for el in path: print(el) if el not in here['children']: here['children'][el] = {'count': 0, 'children': {}} here = here['children'][el] here['count'] = count

Categories : Python

Django, python sorting nested dictionary by date key
Custom template tag was the solution but i was using it wrong in the template. The below usage is true. Custom template tag: @register.filter(name='sort') def listsort(value): if isinstance(value, dict): new_dict = SortedDict() key_list = value.keys() key_list.sort() for key in key_list: new_dict[key] = value[key] return new_dict elif isinstance(value, list): new_list = list(value) new_list.sort() return new_list else: return value listsort.is_safe = True The correct usage in the template : {% for venue, days in program.items %} <div style='float:left; clear:both;'> <div class='boxRedBottom' style='width:100px;'>

Categories : Django

Python Deeply Nested Dictionary of a Specific Type
This approach is similar to your first example, except you can specify whatever depth you want without a lot of typing. from collections import defaultdict def nested_default_dict(num_keys, init_func): if num_keys == 1: return defaultdict(init_func) else: return defaultdict(lambda: nested_default_dict(num_keys-1, init_func)) foo = nested_default_dict(5, set) foo[1][2][3][4][5].add("Hello World") foo[1][2][3][4][5].add("Lorem Ipsum") foo[1][2][3][4][5].add("Dolor sit amet") print foo[1][2][3][4][5] bar = nested_default_dict(3, list) bar[4][8][15].append(16) bar[4][8][15].append(23) bar[4][8][15].append(42) print bar[4][8][15] Result: set(['Dolor sit amet', 'Lorem Ipsum', 'Hello World']) [16, 23, 42] One drawback is that the dicts don't look very pretty when

Categories : Python

Dictionary comprehension nested for loop not working as planned
What am I missing about dictionaries? The keys are unique. You can read about dictionaries in the docs here: http://docs.python.org/2/library/stdtypes.html#mapping-types-dict

Categories : Python

fetch documents from mongodb collection by querying nested dictionary in mongo
You can use the $exists operator and dot notation to do this, but you need to build up your query dynamically like this (in the shell): var user = 'abc'; var query = {}; query['user_details.' + user] = { $exists: true }; db.coll.find(query);

Categories : Python

Issue with Dictionary type, If gived a specific text then get the equivalent dictionary key or dictionary value?
If this were my application, I would change the UI element to a datagridview so that I could bind a collection containing a custom class and just hide or show the appropriate columns as needed. This approach will allow you to easily add additional property columns in the future without worrying about the problems you are currently facing. It would also allow you to extend the UI to other platforms (mobile, web) without a lot of hard-coded information in the UI. For example, I would create the following class and collection to hold info about the files: Public Class FileDetails Public Property Index As Integer Public Property Description As String = String.Empty Public Property FullFileName As String = String.Empty Public ReadOnly Property FileName As String Get

Categories : Dotnet

Read initially unknown number of N lines from file in a nested dictionary and start in next iteration at line N+1
You could use a dictionary to keep track of all the IDX columns and just add each line's IDX column to the appropriate list in the dictionary, something like: from collections import defaultdict import csv all_lines_dict = defaultdict(list) with open('your_file') as f: csv_reader = csv.reader(f) for line_list in csv_reader: all_lines_dict[line_list[3]].append(line_list) Csv reader is part of python standard library, and makes reading csv files easy. It will read each line as a list of its columns. This differs from your requirements because each key is not a dictionary of dictionaries but it is a list of the lines that share the IDX key.

Categories : Python

KeyError 0 when trying to traverse session dictionary in Django
The correct way to iterate over the session's values is request.session.itervalues() - the base session class exposes the same key/value/item options as a standard dictionary. I am unsure so far where it's getting the values your for loop is finding, but it's not the values.

Categories : Python

New dictionary using LINQ to dictionary
var people = positions.Select(x => new { x.Key, Values = x.Value.OfType<Person>().ToList() }) .Where(x => x.Values.Any()) .ToDictionary(x => x.Key, x => x.Values)

Categories : C#

Nested looping over tuple values in a dictionary with tuple keys python
I think you could consider recreating your data as nested dictionaries: >>> result_dict = {} >>> result_dict[(1, 2, 3, 4)] = "test" >>> result_dict[(1, 2, 4, 4)] = "test2" >>> result_dict {(1, 2, 3, 4): 'test', (1, 2, 4, 4): 'test2'} >>> result_dict2 = {} >>> for (a, b, c, d), k in result_dict.iteritems(): ... result_dict2.setdefault(a, {}).setdefault(b, {}).setdefault(c, {})[d] = k ... >>> result_dict2 {1: {2: {3: {4: 'test'}, 4: {4: 'test2'}}}} then you can iterate over the keys on any level: for _, a in result_dict2.iteritems(): for _, b in a.iteritems(): for _, c in b.iteritems(): for _, d in c.iteritems(): # do something

Categories : Python

updating list values of dictionary with the values of another dictionary and printing the result as the values of first dictionary in python
Well, first off your syntax for defining literal dictionaries is incorrect. Dictionaries are surrounded by curly brackets like this: {} instead of square brackets like this: [] If you want 'Standard_Animator' and 'Extended_Animator' to be keys for lists of colors, you would want to do something like this: legenddict = {"Standard_Animator" : ["blue", 3f7fff, 00bfff, 3fffbf, "green", bfff3f, ffbf00, ff7f00, "red"], "Extended_Animator" : ["lightgray", "blue", 3f7fff, 00bfff, 3fffbf, "green", bfff3f, ffbf00, ff7f00, "red", "magenta"} colordict = {'blue':'ff00ff', 'red':'808080', 'lightgray':'d3d3d3', 'magenta':'00ff00'} So, to print the values in legenddict using the color names in colordict, you can check to see if the colors are keys in colordict, and if so, look up the

Categories : Python

Traverse a nested list with Javascript/jQuery and store in array
I've modified your original code. This should work for all combinations of nested lists. Instead of using children().get(), I used the native JS child methods. It will traverse everything in the list, but ignore elements unless they are <li> or <ul>. Good luck. var count = 0; var pages = []; var parentStack = []; var result = {}; parentStack.push(0); function createNewLevel(obj) { var obj = obj || document.getElementById('sortableSitemap'); if (obj.tagName == 'LI') { ++count; pages.push({ pId: parentStack[parentStack.length - 1], urlStr: obj.id, myId: count });

Categories : Javascript

Dictionary to XML using LINQ
This will generate xml in format you want: new XElement("UserClassDictionary", from kvp in UserClassDict select new XElement("User", new XAttribute("id", kvp.Key), new XElement("ControlNumbers", from cn in kvp.Value.ControlNumber select new XElement("ControlNumber", cn) ) );

Categories : C#

Python ordered dictionary: Why is [] notation required to change dictionary values using a for loop?
In the loop, name and val are bound to each of the objects in the mapping in turn. Simply rebinding the names will not modify the original iterable.

Categories : Python

SignalR Adding/Removing Connections from a dictionary and finding Group values from dictionary
First of all, SignalR is pretty smart about not wasting resources when sending to groups without any subscriptions, so you should be fine sending to groups without any members as long as it's OK to waste a few cycles doing that. If you don't have too many organizations you can have a ConcurrentDictionary<int,int> with all your organization ids as your keys and the number of connected members as your value. In OnConnected and OnDisconnected in could use Interlocked.Increment and Interlocked.Decrement respectively to keep track of the currently connected members. Then in your task could loop over the keys and skip any organization with zero connected members. This new ConcurrentDictionary could replace _uniqueOrganizations if you don't mind calling key.ToString(CultureInfo.InvariantC

Categories : Asp Net

How can I implement a fuzzy search across each value of a dictionary in a multiple dictionary list?
You can use something like >>> l = [ ... {"Name":"Arnold", "Age":"52", "Height":"160"}, ... {"Name":"Donald", "Age":"52", "Height":"161"}, ... {"Name":"Trevor", "Age":"22", "Height":"150"} ... ] >>> >>> [d for d in l if any("nol" in v for v in d.values())] [{'Age': '52', 'Name': 'Arnold', 'Height': '160'}] >>> >>> [d for d in l if any("52" in v for v in d.values())] [{'Age': '52', 'Name': 'Arnold', 'Height': '160'}, {'Age': '52', 'Name': 'Donald', 'Height': '161'}]

Categories : Python

Check if dictionary key contains any of another dictionary's keys and print matching pairs
This worked for me: full_name1 = 'Will Smith' full_name2 = 'Matt Damon' full_name3 = 'Mark yMark' name1 = 'Will' name2 = 'Matt' name3 = 'Mark' my_dict = {full_name1 : 1, full_name2 : 2, full_name3 : 3} another_dict = {name1 : 'x', name2 : 'y', name3 : 'z'} result = {} for sub, val in another_dict.items(): # start with the substrings for string, key in my_dict.items(): if sub in string: result[key]=val print(result) I used dict.items() to make the code a bit more readable. Combined with some more clear variable names, I think that makes the logic a bit easier to follow. docs: http://docs.python.org/2/library/stdtypes.html#dict.items Could be simplified I'm sure. Note that I assumed that your words like

Categories : Python

Get the first occurance in a dictionary LINQ
If you know that there'll always be at least one such benefit - or you don't mind using a placeholder for a missing value - you can use something like this: Caption = string.Format("{0}_{1}", benefits.Where(b => b.Key == p.BenefitID) .Select(b => b.Value) .FirstOrDefault(), // Or First p.Name); I'd advise you not to mix and match your query expressions and dot notation so much though - it's quite confusing at the moment.

Categories : C#

Processing a C# Dictionary using LINQ
If you want to group countries by code, then you don't need two dictionaries. Use Enumerable.GroupBy foreach(var codeGroup in countries.GroupBy(c => c.CountryCode)) { foreach(var country in codeGroup) Console.WriteLine(country.CountryName); Console.WriteLine(); } Or just use your countriesDictionary (it already has countries grouped by code): foreach(var kvp in countriesDictionary) { foreach(var country in kvp.Value) Console.WriteLine(country.CountryName); Console.WriteLine(); }

Categories : C#

How can I cast a subset of a dictionary to a type derived from Dictionary<>
You get an invalid cast exception because the result of ToDictionary is not MyDict. In order to fix this problem, add a constructor to MyDict that takes an IDictionary<string,A>, and return the result of calling that constructor from your GetSubSet method: public class MyDict : Dictionary<string, A> { public MyDict() { // Perform the default initialization here ... } public MyDict(IDictionary<string,A> dict) { // Initialize with data from the dict ... } } ... public MyDict GetSubSet(int testVal) { var ret = dict.Where(e => e.Value.aValue == testVal). ToDictionary(k => k.Key, k => k.Value); return new MyDict(ret); }

Categories : C#



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.