w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories
Combine/Add dictionaries in a list when the values for two dictionary are equal in C#
var lookup = dicList.ToLookup(x => new{ Product = x["Product"], Region = x["Region"]}); var condensedDicList = lookup .Select(x => new Dictionary<string, object>(){ {"Product",x.Key.Product}, {"Region",x.Key.Region}, {"Profit",x.Sum(d=>(int)d["Profit"])} }) .ToList(); but seriously... why not write a class with class MyData { public string Product{get;set;} public string Region{get;set;} public int Profit{get;set;} } and save yourself a huge amount of ball-ache.

Categories : C#

How to compare only values in two different dictionaries which belongs to different keys in c#
Test if dictionaries have the same values (but, mayhaps, the different keys) public static Boolean DictionaryHaveEqualValues(IDictionary left, IDictionary right) { if (Object.ReferenceEquals(left, right)) return true; else if (Object.ReferenceEquals(left, null)) return false; else if (Object.ReferenceEquals(right, null)) return false; if (left.Count != right.Count) return false; Dictionary<Object, int> reversed = new Dictionary<Object, int>(); foreach (var value in left.Values) if (reversed.ContainsKey(value)) reversed[value] = reversed[value] + 1; else reversed.Add(value, 1); foreach (var value in right.Values) if (!reversed.ContainsKey(value)) return false; else if (reversed[value] == 1) reversed.Remov

Categories : C#

Does the order of keys in dictionary.keys() in a python dictionary change if the values are changed?
No, a python dictionary has an ordering for the keys but does not guarantee what that order will be or how it is calculated. Which is why they are not guaranteed to be ordered in the first place. The values stored in the dictionary do not have an effect on the hash values of the keys and so will not change ordering. Taken from the Python Documentation: The keys() method of a dictionary object returns a list of all the keys used in the dictionary, in arbitrary order (if you want it sorted, just apply the sorted() function to it). To check whether a single key is in the dictionary, use the in keyword.

Categories : Python

generate list of dictionaries from template dictionary and keys
Answering my own question since I've found that this work: def swapRules2(d,rule): '''clear dict, return new with only rule set''' keys=d.keys() if rule not in keys: raise Exception("wrong key") outd=dict.fromkeys(keys,0) outd[rule]=100 return outd and in the list comprehension it returns the expected output: In [16]: [tr.swapRules2(mydict,jj) for jj in keys] Out[16]: [{'a': 100, 'b': 0, 'c': 0}, {'a': 0, 'b': 0, 'c': 100}, {'a': 0, 'b': 100, 'c': 0}] However, I still do not understand why the previous approach did not.

Categories : Python

Defining a dictionary of dictionaries with vectors as inner and outer keys
Why not have your dictionary like so: matrix = { (v1,v2):val} So for example: >>> m = {((1,2,3,4),(9,8,8,2)):"info"} >>> m[((1,2,3,4),(9,8,8,2))] 'info' If you required a setup like: matrix = { v1: { v2:val }}, you might use a deafultdict like so: >>> matrix = defaultdict(dict) >>> matrix[(1,2,3,4)][(9,8,8,2)] = "info" >>> matrix defaultdict(<type 'dict'>, {(1, 2, 3, 4): {(9, 8, 8, 2): 'info'}}) >>> matrix[(1,2,3,4)][(9,8,8,2)] 'info'

Categories : Python

Match keys from two dictionaries, and make new dictionary with matched key and two associated values
Use a dict-comprehension, dic1.viewkeys() & dic2.viewkeys() returns a set of all common keys from the two dictionaries: >>> dic1 = {1.0: 9.0, 3.0: 33.0, 5.0: 13.0} >>> dic2 = {1.0: 3.4, 3.0: 88.9, 4.0: 73.0, 5.0: 9.0} >>> {k : (dic1[k],dic2[k]) for k in dic1.viewkeys() & dic2.viewkeys()} {1.0: (9.0, 3.4), 3.0: (33.0, 88.9), 5.0: (13.0, 9.0)} For py2.6 and earlier use dict(): >>> dict( (k , (dic1[k],dic2[k])) for k in dic1.viewkeys() & dic2.viewkeys()) {1.0: (9.0, 3.4), 3.0: (33.0, 88.9), 5.0: (13.0, 9.0)} On py3.x use just dict.keys(): >>> {k : (dic1[k],dic2[k]) for k in dic1.keys() & dic2.keys()} {1.0: (9.0, 3.4), 3.0: (33.0, 88.9), 5.0: (13.0, 9.0)}

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

GIven a set of strings, create a dictionary of dictionaries using them as keys to entries with default values
Like this? >>> set_of_strings = {'abc', 'def', 'xyz'} >>> dict_of_dicts = {} >>> for key in set_of_strings: ... dict_of_dicts[key] = {'pr':0, 'wt':0} ... >>> print dict_of_dicts {'xyz': {'pr': 0, 'wt': 0}, 'abc': {'pr': 0, 'wt': 0}, 'def': {'pr': 0, 'wt': 0}} As a dictionary comprehension: >>> {k:{'pr':0, 'wt':0} for k in {'abc', 'def', 'xyz'}} {'xyz': {'pr': 0, 'wt': 0}, 'abc': {'pr': 0, 'wt': 0}, 'def': {'pr': 0, 'wt': 0}} Alternatively, you can do something like: >>> set_of_strings = {'abc', 'def', 'xyz'} >>> value = {'pr': 0, 'wt': 0} >>> dict(zip(set_of_strings, [value]*len(set_of_strings))) {'xyz': {'pr': 0, 'wt': 0}, 'abc': {'pr': 0, 'wt': 0}, 'def': {'pr': 0, 'wt': 0}}

Categories : Python

convert n equal length lists to dictionary with unique keys from one list
Try this: id = ['1','1','1','2','2','2','3','3','3'] a = [1,2,3,4,5,6,7,8,9] b = [10,11,12,13,14,15,16,17,18] c = [20,21,22,23,24,25,26,27,28] from collections import defaultdict d = defaultdict(list) # add as many lists as needed, here n == 3 lsts = [a, b, c] for ki, kl in zip(id, zip(*lsts)): d[ki] += [kl] for k, v in d.items(): # if you don't mind using tuples, simply do this: d[k] = zip(*v) d[k] = map(list, zip(*v)) The result is exactly as expected according to the question: d == {'1':[[1,2,3],[10,11,12],[20,21,22]], '2':[[4,5,6],[13,14,15],[23,24,25]], '3':[[7,8,9],[16,17,18],[26,27,28]]} => True

Categories : Python

Python Two Dictionaries within another Dictionary within another Dictionary
In self.__tests = {'test1' : info.copy(), 'test2' : info.copy(), 'test3' : info.copy()} the variable info is only copied by a shallow (ie non recursive) copy. You should use copy.deepcopy here if you want __tBin and friends to be copied.

Categories : Python

Dictionary of dictionaries in loop in Python
You are rewriting the value for the same fileid. In your code, if re.search(r'мерзавец|подлец', agit_corpus.raw(fileid)): dict_features[fileid] = {'oskorblenie':'1'} else: dict_features[fileid] = {'oskorblenie':'0'} if re.search(r'честны*|труд*', agit_corpus.raw(fileid)): dict_features[fileid] = {'samoprezentacia':'1'} else: dict_features[fileid] = {'samoprezentacia':'0'} For one fileid, you create the first one and then replace it using the second if-else construct. (Both the if-else constructs put values since either the if or the else will always be executed) What you may be looking for is a defaultdict with dict as the default value. Something along the lines of - >>> from collections import defaultdict >>> a = defaultdic

Categories : Python

How to compare two dictionaries `Dictionary and `Dict_Aggregate= `Dictionary` using c#
You'll probably want to do some more extensive comparison, and it depends on whether you care that the values are the same. This bool dictionariesEqual = Dict.Keys.Count == Dict_Aggregate.Keys.Count && Dict.Keys.All(k => Dict_Aggregate.ContainsKey(k); will determine that the keys match; if you want to match the values, you'll have to add another clause and determine how to compare the ints and strings, something like: bool dictionariesEqual = Dict.Keys.Count == Dict_Aggregate.Keys.Count && Dict.Keys.All(k => Dict_Aggregate.ContainsKey(k) && Dict_Aggregate.All(v => { int test; return int.TryParse(v.Value, out test) && Dict[v.Key].Equals(test); }); Obviously there are some edge cases on that last value

Categories : C#

python two dictionaries into one? mixed up keys and values
>>> d1={2:3, 8:19, 6:4, 5:12} >>> d2={2:5, 4:3, 3:9} >>> d12 = {k:v for k,v in d1.items() if k not in d2} >>> d21 = {k:v for k,v in d2.items() if k not in d1} >>> answer = {k:v for k,v in itertools.chain(d12.items(), d21.items())} >>> answer {8: 19, 3: 9, 4: 3, 5: 12, 6: 4} Hope this helps

Categories : Python

Why does this Python list of dictionary only have the keys of the dictionary?
You are not making a list of dicts, you are making a list of dictionary keys from the dictionary, list(dict(...)) returns a list of keys: >>> d = dict(username="x", password="y") >>> list(d) ['username', 'password'] Probably you want to define users this way: users = [dict(username="x", password="y")] or users = [{'username': 'x', 'password': 'y'}]

Categories : Python

What is an efficient way to exchange the order of keys in nested dictionaries in Python?
Like this: >>> mydictionary = {"OuterKey1": {"InnerKey1": "Value1", "InnerKey2": "Value2"}, ... "OuterKey2": {"InnerKey1": "Value3", "InnerKey2": "Value4"}} >>> dict([(k, dict([(k2,mydictionary[k2][k]) for k2 in mydictionary])) ... for k in mydictionary.values()[0]]) {'InnerKey2': {'OuterKey2': 'Value4', 'OuterKey1': 'Value2'}, 'InnerKey1': {'OuterKey2': 'Value3', 'OuterKey1': 'Value1'}}

Categories : Python

Error: String indicies must be integers, list of dictionaries within a dictionary python
for varient_dict in key: iterates over the individual characters in key. You probably want to do for varient_dict in mydict[key]. You could also just use .items(): for key, varient_dict in mydict.items(): if varient_dict["length"] > stats_dict[key]["max length"]: varient_dict["max length"] = stats_dict[key]["length"]

Categories : Python

Is there a good way python to compare complex dictionaries with unkonwn depth & level
You're in luck, I did this as part of a project where I worked. You need a recursive function something like: def checkDifferences(dict_a,dict_b,differences=[]) You can first check for keys that don't exist in one or the other. e.g Expected Name/Tom Actual None Then you compare the types of the values i.e check if the value is a dict or a list etc. If it is then you can recursively call the function using the value as dict_a/b. When calling recursively pass the differences array. If the type of the value is a list and the list may have dictionaries within it then you need to covert the list to a dict and call the function on the converted dictionary. I'm sorry I can't help more but I no longer have access to the source code. Hopefully this is enough to get you started.

Categories : Python

get keys value's from dictionary in python
Using dict.get(key, defaultvalue), you get defaultvalue if key is not in the dictionary. >>> d = {'a': 1, 'b': 2} >>> d.get('a', 0) 1 >>> d.get('z', 0) 0 >>> dictlist = [ ... {'url': 'google.com', 'a': 10, 'content': 'google', 'd': 80, 'f': 1, 'lock': 'dd'}, ... {'url': 'fb.com', 'z': 25, 'content': 'google', 'd': 60, 'p': 1, 'a': 19} ... ] >>> >>> newdictlist = [] >>> sumlist = ['a', 'z', 'd'] >>> for d in dictlist: ... newdict = {} ... newdict['newurl'] = d['url'] ... newdict['newtitle'] = d['content'] ... newdict['sumvalue'] = sum(d.get(key, 0) for key in sumlist) ... newdictlist.append(newdict) ... >>> newdictlist[0] {'newtitle': 'google', 'sumvalue': 90, 'newurl': 'google.

Categories : Python

Python paired dictionary keys()
itertools.combinations can come in handy d = {'Komp': ['values'], 'Forx': ['values'], 'Rove': ['values']} from itertools import combinations for x in combinations(d, 2): print x

Categories : Python

how to iterate over all keys in dictionary python?
word_count_dict["Britain"] is a regular dictionary. Just loop over it: for filename in word_count_dict["Britain"]: if filename == 'total': continue print("Britain appears in {} {} times".format(filename, word_count_dict["Britain"][filename])) or retrieve all the keys with: word_count_dict["Britain"].keys() Do note that you have one special key total in that dictionary. It may be that your indentation is off, but it appears you are not correctly counting your file entries: if file not in word_count_dict[word]: word_count_dict[word][file] = 0 word_count_dict[word][file] += 1 word_count_dict[word]["total"] += 1 would only count (+= 1) words if file had not been seen in the per-word dictionary before; correct that to: if file not in word_cou

Categories : Python

Python dictionary keys. "In" complexity
First, key in d.keys() is guaranteed to give you the same value as key in d for any dict d. And the in operation on a dict, or the dict_keys object you get back from calling keys() on it (in 3.x), is not O(N), it's O(1). There's no real "optimization" going on; it's just that using the hash is the obvious way to implement __contains__ on a hash table, just as it's the obvious way to implement __getitem__. You may ask where this is guaranteed. Well, it's not. Mapping Types defines dict as, basically, a hash table implementation of collections.abc.Mapping. There's nothing stopping someone from creating a hash table implementation of a Mapping, but still providing O(N) searches. But it would be extra work to make such a bad implementation, so why would they? If you really need to prove

Categories : Python

python delete those keys from dictionary who has same value
You can use set and a dict comprehension: >>> dicts = {'met_293': ['81.0175','4','7','7','29.76','23','1','0','22','28.57','2','[KG]EHY'],'met_394': ['79.9579','4','7','7','29.76','18','3','0','15','28.57','2','EHY[ILV]'],'met_309': ['81.0175','4','7','7','29.76','23','1','0','22','28.57','2','[KG]EHY'],'met_387': ['79.9579','4','7','7','29.76','18','3','0','15','28.57','2','EHY[ILV]']} >>> seen = set() >>> {k:v for k,v in dicts.iteritems() if v[11] not in seen and not seen.add(v[11])} {'met_394': ['79.9579', '4', '7', '7', '29.76', '18', '3', '0', '15', '28.57', '2', 'EHY[ILV]'], 'met_293': ['81.0175', '4', '7', '7', '29.76', '23', '1', '0', '22', '28.57', '2', '[KG]EHY']} The above code is equivalent to: >>> dic =

Categories : Python

Perl script to compare two files but print in order
This can be done efficiently in two steps. Let's assume you have been able to find the "lines that match" but they are in the wrong order; then a simple grep can re-organize them. Assuming you have a script matchThem that takes two inputs (file1 and file2) and outputs them to tempFile, then the over all script will be: matchThem file1 file2 > tempFile grep -Fx -f tempFile file1 The -Fx flag means: -F : find exact match only (much faster than wildcards) -x : only match whole lines

Categories : Perl

Sorting alphanumeric keys of a dictionary in python
import re def key_func(s): return [int(x) if x.isdigit() else x for x in re.findall(r'D+|d+', s)] sorted_keys = sorted(d, key=key_func) Example: >>> d = {'01IB0610': 'foo', '01IB062': 'bar', '01IB0604': 'baz'} >>> sorted(d, key=key_func) ['01IB062', '01IB0604', '01IB0610']

Categories : Python

replace dictionary keys (strings) in Python
name_mapping = { 'voornaam': 'first_name', ... } dic = your_dict # Can't iterate over collection being modified, # so change the iterable being iterated. for old, new in name_mapping.iteritems(): value = dic.get(old, None) if value is None: continue dic[new] = value del dic[old]

Categories : Python

Storing a 7millions keys python dictionary in a database
For queries on large tables like this to return quickly, you need to index the relevant columns. In your case I would add this as the primary key. create table test ( Int1 integer, Int2 integer, Int3 integer, Primary key (int1, int2) )

Categories : Python

Randomly Shuffle Keys and Values in Python DIctionary
In [47]: import random In [48]: keys = a.keys() In [49]: values = a.values() In [50]: random.shuffle(values) In [51]: a_shuffled = dict(zip(keys, values)) In [52]: a_shuffled Out[52]: {'one': 2, 'three': 1, 'two': 3} Or, more pithy would be: In [56]: dict(zip(a.keys(), random.sample(a.values(), len(a)))) Out[56]: {'one': 3, 'three': 2, 'two': 1} (but I suppose that is the solution you already came up with.) Note that although using random.sample is pithier, using random.shuffle is a bit faster: import random import string def using_shuffle(a): keys = a.keys() values = a.values() random.shuffle(values) return dict(zip(keys, values)) def using_sample(a): return dict(zip(a.keys(), random.sample(a.values(), len(a)))) N = 10000 keys = [''.join(random.choice(s

Categories : Python

Python Generate a dynamic dictionary from the list of keys
>>> mydict = {} >>> keyList1 = ["Person", "Male", "Boy", "Student", "id_123", "Name"] >>> value1 = "Roger" >>> reduce(lambda x, y: x.setdefault(y, {}), keyList1, mydict) {} >>> mydict["Person"]["Male"]["Boy"]["Student"]["id_123"]["Name"] = value1 You can also do it in one step like this >>> keyList2 = ["Person", "Male", "Boy", "Student", "id_123", "Age"] >>> value2 = 25 >>> reduce(lambda x,y: x.setdefault(y,{}), keyList2[:-1], mydict).update({keyList2[-1]: value2})

Categories : Python

Fast Perl<->Python serialization that supports integer dictionary keys
You can use yaml. >>> import yaml >>> dict_before = {1:'one', 20: 'twenty'} >>> data = yaml.safe_dump(dict_before) >>> dict_after = yaml.safe_load(data) >>> dict_after {1: 'one', 20: 'twenty'} I had similar problem. I wanted to share a configuration file in Perl and Python and I had to use yaml. You can install yaml module in python with: pip install PyYAML Although, integer keys will be converted to string in perl => legal values for perl hash key

Categories : Python

Python: How to check if keys exists and retrieve value from Dictionary in descending priority
One option is to use chained gets: value = myDict.get('lastName', myDict.get('firstName', myDict.get('userName'))) But if you have keySet defined, this might be clearer: value = None for key in keySet: if key in myDict: value = myDict[key] break

Categories : Python

Print all Unique Values in a Python Dictionary
Use a set(): from itertools import chain unique_values = set(chain.from_iterable(d.values() for d in dictionaries_list)) for value in unique_values: print(value) print(len(unique_values)) Use .itervalues() on Python 2 for a little more efficiency. Because you have a list of dictionaries, we need to pull out the values from each of those dictionaries first; I used itertools.chain.from_iterable() with a generator expression to list all values in a sequence: >>> for value in set(chain.from_iterable(d.values() for d in dictionaries_list)): ... print(value) ... news sports movies music The alternative is to use nested loops in the generator expression: >>> for value in set(v for d in dictionaries_list for v in d.values()): ... print(value) ... news sport

Categories : Python

super simple cipher function in python. comparing a list to keys in a dictionary
Your for loop should iterate through x, not d. def code_scram(x): c = {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f', 7: 'g', 8: 'h', 9: 'i', 10: 'j', 11: 'k', 12: 'l', 13: 'm', 14: 'n', 15: 'o', 16: 'p', 17: 'q', 18: 'r', 19: 's', 20: 't', 21: 'u', 22: 'v', 23: 'w', 24: 'x', 25: 'y', 26: 'z'} scram = "" for i in x: if i in c: scram += c[i] return scram print code_scram([1,2,3,4]) Result: abcd The function only works for lists, so passing in the integer d won't work. Pass in a list instead. d = [1] print code_scram(d) If you want the function to work for lists and lone integers, you can perform a type check, and convert as necessary. def code_scram(x): if isinstance(x, int): x = [x] c = {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e',

Categories : Python

Python create Counter object from dictionary, include a sum of values against summarised keys
You are not using the full Counter API here, may as well replace that with a defaultdict from collections import defaultdict stats = defaultdict(lambda: [0, 0]) for entry in mydict.values(): counts = stats[tuple(entry[:2])] counts[0] += 1 counts[1] += entry[-1] then printing: for (initials, date), (count, area) in stats.iteritems(): print ', '.join((initials, date, str(count), str(area))) which outputs: OV, 2012-06-14, 1, 4 AM, 2012-06-13, 1, 3 JN, 2012-06-13, 2, 7

Categories : Python

Print data from Python dictionary based on variable?
To answer your specific question, you want to use decore[rcore] to read the value of rcore from dictionary decore. However, as has already been suggested to you, use of processor affinities may not be the best way for you to go forward. This is because rather than processors, what you are seeing is cores, and task migration between cores will not hurt your application much with cache misses. Processor affinity on the other hand could prevent quicker scheduling for your process and hence degrade performance.

Categories : Python

Bash script compare values from 2 files and print output values from one file
I do not see how you get your output. Where does 120.172.168.36 come from. Here is one solution to compare awk -F, 'NR==FNR {a[$0]++;next} !a[$1] {print $1}' file2 file1 114.4.21.198 114.4.21.205 114.4.21.205 114.4.21.213

Categories : Bash

How to compare two xml files in python in script?
I think you're looking for the filecmp module. You can use it like this: import filecmp cmp = filecmp.cmp('f1.xml', 'f2.xml') # Files are equal if cmp: continue else: out_file.write('f1.xml') Replace f1.xml and f2.xml with your xml files.

Categories : Python

Creating a dictionary with values identical to keys from another dictionary
Use a dict comprehension: dict2 = {k: k for k in dict1} This simply loops over all the keys of dict1 and echos that key as the value as well for each key-value pair.

Categories : Python

What can cause dictionary.ContainsKey(dictionary.Keys.First()) to return false?
The key was first added to the Dictionary<,> when it had one hash code. After that the object was "mutated" to give a state where the hash code is some new number. The Dictionary<,> is therefore in an invalid state. Do not mutate an object that might be a key in some hashtable somewhere, in a way the changes the hash code of that object.

Categories : C#

Get max keys of a list of dictionaries
Use collection.Counter() objects instead, or convert your dictionaries: from collections import Counter result = Counter() for d in dicts: result |= Counter(d) or even: from collections import Counter from operator import or_ result = reduce(or_, map(Counter, dicts), Counter()) Counter objects support finding the maximum per key natively through the | operation; & gives you the minimum. Demo: >>> result = Counter() >>> for d in dicts: ... result |= Counter(d) ... >>> result Counter({'a': 11, 'c': 10, 'b': 7}) or using the reduce() version: >>> reduce(or_, map(Counter, dicts), Counter()) Counter({'a': 11, 'c': 10, 'b': 7})

Categories : Python

Navigate Python Script in IDLE without Arrow Keys
You can configure IDLE this way: Open up the menu item Options -> Configure IDLE... Go to Keys tab In the drop down menu on the right side of the dialog change the select to "IDLE Classic Unix"

Categories : Python



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