Menu
  • HOME
  • TAGS

Getting keyValuePair based on filtering of keys

c#,dictionary

var dict = new Dictionary<string, long>(); Something like: IEnumerable<long> myvalues = dict.Where(x => x.Key == "A" || x.Key == "B") .Select(x => x.Value); that will return the Values you wanted or IEnumerable<KeyValuePair<string, long>> myvalues = dict.Where(x => x.Key == "A" || x.Key == "B"); The last will return the full...

How to deal with apostrophe when passing dicts from view to template?

javascript,django,dictionary,apostrophe

You need to first convert the dictionaries to JSON: json.dumps(node_result)) and then in your template you should turn off the auto escape: {% autoescape off %} var nodes = {{node_result}}; var links = {{edge_result}}; {% endautoescape %} You can also do : var nodes = {{ node_result|safe }}; var links...

VBA dictionary data type

excel-vba,dictionary,key

No problem here: Sub Tester() Dim d, k Set d = CreateObject("scripting.dictionary") d.Add 1, 1 d.Add "a", 2 d.Add #1/2/1978#, 3 d.Add CDbl(66), 4 d.Add CSng(99), 5 d.Add True, 6 For Each k In d.keys Debug.Print TypeName(k), k, d(k) Next k End Sub Output: Integer 1 1 String a 2...

Implementing a dictionary function to calculate the average of a list

python,list,dictionary

I think you want something more like: print("Enter positive, negative or zero to determine the average: ") # get list of values/numbers from the user values = [i for i in iter(lambda: int(input("Enter a number (-9999 to end): ")), -9999)] -9999 is the sentinel value to break the loop def...

PHP / MySQL: How to store Select results in array

php,mysql,arrays,dictionary,key

if($translations->num_rows > 0){ $result_arr = array(); echo "<table><tr><th>ID</th><th>Translation</th></tr>"; while($translation = $translations->fetch_assoc()){ echo "<tr><td>" . $translation["ID"] . "</td><td>" . $translation["German"] . "</td></tr>"; $result_arr[] = $translation; } echo "</table>"; }else{ echo "0 results"; } // now you can iterate $result_arr foreach($result_arr as $row){ echo "<tr><td>" . $row["ID"] ....

dict.fromkeys return dictionary in reverse order from a list [duplicate]

python,dictionary

Dictionaries are unordered. Use a OrderedDict if order is important: from collections import OrderedDict kwargs=OrderedDict((k, None) for k in template_vars) ...

c++ : double iteration through map

c++,dictionary,iterator

You can use std::next to do this: for(auto element1 = myMap.begin() ; element1 != myMap.end() ; ++element1) { for(auto element2 = std::next(element1) ; element2 != myMap.end() ; ++element2) { //my stuff } } Here is some additional background information about std::next. std::next has an optional second argument which is the...

Compare dictionary key, values with nested list elements - Python

python,dictionary,nested-lists

I would group the sublists in a dict by the first element which is the letter then iterate over your original dict and check if each key is in the grouping dict and do your comparison. d = {'a': [1, 5], 'c': [7, 9], 'f': [10, 12], 'b': [15, 20]}...

Compiler modifying a variable without adressing it

c#,variables,dictionary

What you are currently doing: Dict2 = Dict1; Is reference copying, so both Dict1 and Dict2 are pointing to the same location. You can create a new copy like: Dict2 = Dict1.ToDictionary(d=> d.Key, d=> d.Value); Remember, if your Key and Value are custom objects (based on some class), in that...

Inheritance: Set Values of Abstract Dictionary

c#,.net,inheritance,dictionary

Of course it doesn't change - you're always returning a different Dictonary! You'll have to return an existing dictionary (for example, by storing the dictionary in a field) to have it (effectively) mutable. Dictionary<string, column> _columnNames = new Dictionary<string, column>{ {"partID", new column{ name = "ID", show = false, type...

Python key error - for key in dictionary: dictionary[key]

python,dictionary,key,keyerror

If your objects implement __eq__ and __hash__, you have to make sure that the hash value does not change after the object is created. If you mutate your objects after creating them, you can get them into an inconsistent state where the hash value stored for them in a dictionary...

ValueError: dictionary update sequence element #0 has length 1; 2 is required while reading from file

python,file,dictionary

dict() does not parse Python dictionary literal syntax; it won't take a string and interpret its contents. It can only take another dictionary or a sequence of key-value pairs, your line doesn't match those criteria. You'll need to use the ast.literal_eval() function instead here: from ast import literal_eval if line.startswith(self.kind):...

Most common dictionary in array of dictionaries

arrays,swift,dictionary

You could use a NSCountedSet which provides this kind of functionality: let arr = [ [ "foo": "bar" ], [ "foo": "bar" ], [ "foo": "baz" ], ] let countedSet = NSCountedSet(array: arr) for dict in countedSet { println(countedSet.countForObject(dict)) println(dict) } prints 2 ["foo": "bar"] 1 ["foo": "baz"] If you're...

Using IEnumerable.Except on KeyCollection vs. exploiting Dictionary.ContainsKey for mutual subtractions and intersection in relation to performance

c#,algorithm,dictionary

Your reasoning looks sound to me. LINQs Except() iterates over the first collection putting it into a HashSet before iterating over the second collection, performing lookups against the HashSet - it is O(n + m). Your extension method is therefore O(n + m) too. As you mention, if you want...

Pygame 3D: How to and is it possible?

python,performance,dictionary,3d,pygame

Pygame doesn't have the ability to do this natively. If you really want this, you'll need to brush up on your trigonometry to map lines from the 3D space to the 2D screen. At that point, you'll essentially be re-implementing a 3D engine.

How to find the difference between two lists of dictionaries checking the key-value pair

python,list,csv,dictionary

Part of this solution was found by OP as per our last CHAT conversation, it was to convert a string into dictionary using ast module. Now using this module to convert every row read by the csv.reader() as it returns a list of strings, which would be a list of...

What is the Pythonic way to iterate over set intersection and exclusions?

python,dictionary,set,iteration,set-intersection

You are making it way too complicated for yourself. You appear to be creating default values for missing keys, so the following is far simpler: for key in dict_A.viewkeys() | dict_A.viewkeys(): some_function(dict_A.get(key, 0), dict_B.get(key, 0)) using the dict.get() function to substitute a default for a missing key. Note that I...

What's the fastest way to compare point elements with each other?I have used Nested for loop to do that, but it's very slow

c++,opencv,for-loop,dictionary,vector

for 20000 random points with about 27 neighbors for each point this function gave me a speed-up. It needed about 33% less time than your original method. std::vector<std::vector<cv::Point> > findNeighborsOptimized(std::vector<cv::Point> p, float maxDistance = 3.0f) { std::vector<std::vector<cv::Point> > centerbox(p.size()); // already create a output vector for each input point /*...

Divide each python dictionary value by total value

python,dictionary

Sum the values, then use a dictionary comprehension to produce a new dictionary with the normalised values: total = sum(a.itervalues(), 0.0) a = {k: v / total for k, v in a.iteritems()} You can squeeze that into a one-liner, but it won't be as readable: a = {k: v /...

Reaching into a nested dictionary several levels deep (that might not exist)

python,dictionary

You can use a recursive function: def get_value(mydict, keys): if not keys: return mydict if keys[0] not in mydict: return 0 return get_value(mydict[keys[0]], keys[1:]) If keys can not only be missing, but be other, non-dict types, you can handle this like so: def get_value(mydict, keys): if not keys: return mydict...

dict.setdefault(key, []).append() --> get rid of additional list

python,dictionary

You want .extend rather than .append - the former adds a list of items to a list, the latter adds a single item - so if you pass it a list, it adds the list as a single subitem.

Template C++: How to access iterator value for both std::map and std::set?

c++,templates,dictionary,stl,set

You can use template function overload to distinguish these cases: template <typename V> inline V get_value(const V& v) { return v; } template <typename K, typename V> inline V get_value(const std::pair<K, V>& p) { return p.second; } and then found = get_value(*iter); LIVE DEMO...

Specific rows from CSV as dictionary and logic when keys are the same - Python

python,csv,dictionary

You can build the whole dictionary first, with the lists containing all the values for each key. Then once the dictionary is made, you can go through every key and take the largest and smallest values. yourdict = dict() with open(file) as f: filedata = f.read().splitlines() for line in filedata:...

Sorting a dictionary value which is a list of objects by given fields

c#,linq,sorting,dictionary

You can use List.Sort, LINQ doesn't work in this case because you can't modify the dictionary(f.e. Add or using the Value property) during enumeration: foreach(var kv in yourSortedDictionary) { kv.Value.Sort((p1, p2) => { int diff = p1.LastName.CompareTo(p2.LastName); if(diff != 0) return diff; return p1.FirstName.CompareTo(p2.FirstName); }); } This works even if...

using enumerate to iterate over a dictionary of lists to extract information

python,dictionary,enumerate

To try to provide some help for this question: a critical part of the problem is that I don't think enumerate does what you think it does. Enumerate just numbers the things you are iterating over. So when you go through your for loop, sd will first be 0, then...

Python do a lookup between 2 dictionaries

python-2.7,dictionary,lookup

Just iterate the keys and values of the first dict and add the values from the second dict corresponding to the same key. mydict = {41100: 'Health Grant', 50050: 'Salaries', 50150: 'Salaries', 50300: 'Salaries'}; mytb = {'': '', 41100: -3450200.40, 50050: 1918593.96, 50150: 97.50, 50300: 8570.80} result = {} for...

How to collect data from text file to dict in Python?

python,python-2.7,csv,dictionary

I think I understand the table that you have, but if the following does not work let me know. I have tried to make this code as generic as possible (i.e. reading in the header line and not assuming 4 bases as header so this could work for say a...

parse a dot seperated string into dictionary variable

python,string,dictionary

eval is fairly dangerous here, since this is untrusted input. You could use regex to grab the dict name and key names and look them up using vars and dict.get. import re a = {'b': {'c': True}} in_ = 'a.b.c' match = re.match( r"""(?P<dict> # begin named group 'dict' [^.]+...

How can I correct my code to produce a nested dictionary?

python,dictionary

In your code on every loop dictionary is re-initialized. You need to initialize the dictionary first and then add items to it for i in kinetic_parameters: d[i[1]]={} for i in kinetic_parameters: d[i[1]][i[2]]=i[3] or check it before initializing for i in kinetic_parameters: if d.get(i[1]) is None: d[i[1]]={} d[i[1]][i[2]]=i[3] ...

choice between map or unordered_map for keys consisting of calculated double values.

c++,dictionary,hash,unordered-map,comparison-operators

"is it possible to write a Hash function for four doubles (or even just a regular double) that takes a comparison error tolerance into account." No, it is not. That sounds like a very definite statement, how can I be so sure? Let's assume you want a tolerance of 0.00001....

C++ Unordered Map

c++,dictionary,stl,unordered-map

You cannot say c.find(k-x) Because k is an int and x is a std::pair<int, int>. Do you mean one of these two? c.find(k - x.first) Or c.find(k - x.second) As a side note, it is generally unsafe to directly derefernce the returned iterator from find because if find returns .end()...

Create Dictionary from Penn Treebank Corpus sample from NLTK?

python,dictionary,nlp,nltk,corpus

Quick solution: >>> from nltk.corpus import treebank >>> from nltk import ConditionalFreqDist as cfd >>> from itertools import chain >>> treebank_tagged_words = list(chain(*list(chain(*[[tree.pos() for tree in treebank.parsed_sents(pf)] for pf in treebank.fileids()])))) >>> wordcounts = cfd(treebank_tagged_words) >>> treebank_tagged_words[0] (u'Pierre', u'NNP') >>> wordcounts[u'Pierre'] FreqDist({u'NNP': 1}) >>> treebank_tagged_words[100] (u'asbestos', u'NN')...

Swift Dictionary with Protocol Type as Key

ios,osx,swift,dictionary,protocols

I would probably think in the direction of: protocol SCResourceModel { var hashValue: Int { get } func isEqualTo(another: SCResourceModel) -> Bool // ... } struct SCResourceModelWrapper: Equatable, Hashable { let model: SCResourceModel var hashValue: Int { return model.hashValue ^ "\(model.dynamicType)".hashValue } } func == (lhs: SCResourceModelWrapper, rhs: SCResourceModelWrapper) ->...

How to pass the instance itself to an external map at the moment of its creation?

c++,dictionary,constructor,instance

If your Object has value semantic then just assign *this (the object) and not this. On the other hand if identity counts then build a map to Object * (or, better std::shared_ptr) and then the assignment will work as is...

Find last entry in a map

c++,qt,dictionary

Use lastKey: const Key & QMap::lastKey() const Returns a reference to the largest key in the map. This function assumes that the map is not empty. This executes in logarithmic time. This function was introduced in Qt 5.2. As in: qreal last = myMap.lastKey(); ...

Reading unformatted name/value pairs from a file, formatting it, and printing it out in Python 2 dictionary [closed]

python,python-2.7,dictionary,io

This will ignore any lines without a '=', then from the remaining lines, remove any quotes and whitespace on the outside of each key and value, then put it into a dict: data = {} with open('in.txt', 'r') as fh: for line in fh: if '=' not in line: continue...

Matching key/value pairs in two dictionaries and creating a third one

python,loops,dictionary

The problem is this line matched = {i: data1[i]} It is overwriting the previous values of the dictionary. It should be matched[i] = data1[i] Or you can use update matched.update({i: data1[i]}) ...

Swift func - Does not conform to protocol “Boolean Type”

function,swift,dictionary

You don't need to add parameters into return like this (isGot: Bool, dictLocations: Dictionary <String, Double>). you just need to tell compiler that what type this function will return. Here is the correct way to achieve that: func getRecordNumber(recordNumber: Int32) -> (Bool, Dictionary <String, Double>) { let isGot = Bool()...

Model to LazyMap

dictionary,groovy,deserialization

You can use jackson-databind. E.g. @Grab('com.fasterxml.jackson.core:jackson-databind:2.5.4') import com.fasterxml.jackson.databind.ObjectMapper class AccessCredentials { String userName = 'Between The Buried And Me' String password = 'Alaska' LoginOptions loginOptions = new LoginOptions() } class LoginOptions { String partnerId = 'Colors' String applicationId = 'The Great Misdirect' } def mapper = new ObjectMapper() assert mapper.convertValue(new...

How to find the maximum “depth” of a python dictionary or JSON object?

python,json,dictionary

Here's one implementation: def depth(x): if type(x) is dict and x: return 1 + max(depth(x[a]) for a in x) if type(x) is list and x: return 1 + max(depth(a) for a in x) return 0 ...

Replace some string in some phrases using a dictionary of strings in Python

python,dictionary

Just join all the elements in the color list with | as delimiter and pass it as regex in re.sub function. (?i) helps to do case-insensitive match and \b helps to match an exact word. import re color=['black', 'white', 'Blue'] s = "this is a phrase and it contains Blue"...

Does the HashMap class have an Iterator to prevent a ConcurrentModificationException from being thrown? [duplicate]

java,dictionary,concurrentmodification

As you guessed, you need an iterator for removing items during iteration. The way to do it with a Map is to iterate the entrySet() (or, alternatively, the keySet(), if you only need to evaluate the key): Iterator<Map.Entry<String, String>> entryIter = map.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, String> entry = iter.next();...

Find out Key of c# Dictionary when Any() returns true

c#,dictionary

Following should help: If you just need the first /default entry DatFileListDictioanry.FirstOrDefault(t => IsThisDatFileNotInSync(t.Key)) If you need the complete list then: DatFileListDictioanry.Where(t => IsThisDatFileNotInSync(t.Key)) ...

Python RuntimeError: maximum recursion depth exceeded in cmp

python,list,dictionary,recursion

It's a bug. Fixed in 0.15.0 You're passing in empty arrays, and the function handles it incorrectly. Either update your Scipy, or skip if the arrays are empty (though check that your data isn't wrong and that it makes sense to have an empty array there). Some suggestions for your...

Exception when attempting to modify Dictionary

c#,exception,dictionary

you can not modify an IEnumerable while you are enumerating over it. you can do a simple hack and get a copy of what you are enumerating so changes in it does not result in System.InvalidOperationException. for example instead of foreach( Guid id in threads.Keys) use foreach( Guid id in...

Trying to fill a SVG map from wordpress custom categories

wordpress,dictionary,svg

Using the Advanced Custom Fields plugin, you can add custom fields to categories (“taxonomy terms” in WP lingo) as well. And the get_field function provided by the plugin allows you to query the value of such a field for every object you might have attached it to – you just...

Python3 create files from dictionary

file,python-3.x,dictionary

Remove the if not len(key) != len(aDict) and the break. What you probably wanted to do is stopping the loop after iterating all the keys. However key is one of 'OG_1', 'OG_2', 'OG_XX', it's not a counter or something like that. Replace open("key", "w") with open(key + ".txt", "w")....

Although maps are always reference types, what if they're returned from a non-pointer receiver?

pointers,dictionary,go

Why won't you just check it? emp := ExampleMapHolder{make(map[string]int)} m := emp.TheMap() m["a"] = 1 fmt.Println(emp) // Prints {map[a:1]} Playground: http://play.golang.org/p/jGZqFr97_y...

Pandas map to DataFrame from dictionary

python,dictionary,pandas

I doubt this is the most elegant way, but it should do the trick: df['fbm'] = df['name'] for i in companies: df.loc[ df.name.str.contains(i), 'fbm' ] = companies[i] name fbm 0 BULL AXP UN X3 VON American Express 1 BEAR AXP UN X3 VON American Express 2 BULL GOOG UN X5...

How to expand a string within a string in python?

python,string,dictionary,concatenation,list-comprehension

You can do this using split and simple list comprehension: def expand_input(input): temp = input.split("*") return [temp[0]+x for x in temp[1:]] print(expand_input("yyy*a*b*c")) >>> ['yyya', 'yyyb', 'yyyc'] ...

Create huge dictionary

c#,arrays,dictionary

100000000000 bools means ~93 GB of memory. You only have @50 GB (including the default allocated virtual memory). Storing them as bits (not as bytes), would get you down to ~12GB. Look at System.Collection.BitArray...

Thread synchronisation for C++ map

c++,multithreading,dictionary,pthreads

I understand that reading using the [] operator, or even modifying the elements with it is thread safe, but the rest of the operations are not. Do I understand this correctly? Well, what you've said isn't quite true. Concurrent readers can use [] to access existing elements, or use...

C++ Create shared_ptr from Object

c++,c++11,dictionary,shared-ptr

You can simply construct the shared pointer first rather than inline when inserting it into the map. House& Obj::CreateHouse(const char *name) { // make the ptr first! auto aaa = std::make_shared<House>("apartment"); _myHouseMap.insert(std::make_pair("apartment", aaa)); return *aaa; } ...

How to find exact place for given value in python dictionary?

python,dictionary

Given the boundary values is from 1 to 30. row always 10 seats... you're better of building a list of the values, then indexing, eg: seats = ''.join(row * 10 for row in 'ABC') # add DEFG etc.. for additional rows try: print seats[15] # note Python indices are 0...

Multi dimensional python dictionary [duplicate]

python,list,dictionary

You can create a recursive collections.defaultdict based structure, like this >>> from collections import defaultdict >>> nesteddict = lambda: defaultdict(nesteddict) >>> >>> test = nesteddict() >>> test['SYSTEM']['home']['GET'] = True >>> test['SYSTEM']['home']['POST'] = False >>> >>> test['SYSTEM']['home']['GET'] True >>> test['SYSTEM']['home']['POST'] False Whenever you access a key in test, which is not...

How to return random dictionary

arrays,swift,dictionary,random

Your list of dictionaries is not declared correctly. Instead of being : var theDare: [String: String, String: Bool;] It should be : var theDare: [[String: AnyObject]] as you always have String keys but sometimes have String values and sometimes Bool values. Your randomDare() function return needs to be changed accordingly...

How to check bool inside of dictionary

arrays,swift,dictionary,random

Your check should be done by using dictionary subscript method with String parameter because your dictionary keys are Strings. Also since your sure that darePersons exits in your dictionary and its value is Bool you can force unwrap both of them if dare.randomDare()["darePerson"]! as! Bool{ println("dare person is true") }...

IDE doesn't recognize the method

c++,dictionary,hash,qt-creator,code-completion

This feature does not seem to be supported by Qt Creator. There's an open issue about it on http://bugreports.qt.io/. It does work when using the ClangCodeModel plugin though. To use it, go to Help > About Plugins and activate the plugin there: Then, enable its use in the options. Tools...

Determine location given a dictionary with lists inside of a list

python,dictionary

If your list in the dictionary is ordered then this method will work The enumerate method provides two output one will be index and the next one will be value . Since the value here is list we are iterating over the lists[one list at a time ]. We are...

TypeError: 'generator' object has no attribute '__getitem__'

python,python-2.7,dictionary,yield,yield-return

Generator returns an iterator, you explicitly needs to call next on it. Your last line of code should be something like - rows_generator = genSearch(SearchInfo) row2 = next(rows_generator, None) print row2['SearchDate'] ...

Sending a dictionary of javascript parameters to MVC Controller via JSON

javascript,c#,json,asp.net-mvc,dictionary

If your model is strict, you will need to make objects for every sub objects. But if you have a dynamic model, you can read the raw string from your request and parse it with Json.net. public ActionResult Test(string model) { Request.InputStream.Seek(0, SeekOrigin.Begin); string jsonData = new StreamReader(Request.InputStream).ReadToEnd(); var dynamicObject...

How convert any record into a map/dictionary in F#?

dictionary,f#,converter,record

In practice, the best advice is probably to use some existing serialization library like FsPickler. However, if you really want to write your own serialization for records, then GetRecordFields (as mentioned in the comments) is the way to go. The following takes a record and creates a map from string...

Add to value in Dictionary

c#,dictionary

Something like this? myDictionary[myProduct] += stockIncrease; It's pretty much exactly the syntax as you would use to update an item in an array. If it helps, think of it less in terms of "I want to the stock to go up" and more in terms of "how do I get...

How to loop through multi-level json

python,json,dictionary

The issue is that your current k_uid variable and print k_uid command are outside a container loop that cycles through the containers. To print your desired output, you need a loop like the following: for container in K_Containers['La311Containers']: print container['Name'] In a stand-alone context from your other loops this would...

References to mutables (e.g., lists) as values in Python dictionaries - what is best practice?

python,list,dictionary

As I understand your question, the answer is that it depends what you want to do. If you want to set the dictionary value to an independent copy of some other value, then make a copy. If you want to set it to the same object, then don't make a...

Sorting a list with dictionaries, django

python,django,list,sorting,dictionary

You should just be able to do: sorted_objects = sorted(objdict, key=lambda k: k['thing1']) will get you ascending order. For descending: sorted_objects = sorted(objdict, key=lambda k: k['thing1'], reverse=True) ...

Conditional zip of two lists

python,dictionary

As Martijn points out in the comments, you just want OrderedDict((k, v) for k, v in zip(list_1, list_2) if v is not None).

Reach dictionary data within dictionary

swift,dictionary

The problem is that accessing a Dictionary via its subscript, returns an Optional. You'll need to unwrap it first. Testing on a Playground (Swift 1.2) this code works: var activeCustomers = Dictionary<Int, Dictionary<Int, Dictionary<String, String>>>() var d1 = ["a": "b", "c": "d"] var d2 = [1: d1] activeCustomers = [1:...

How do I filter out non-string keys in a dictionary in Python?

python,dictionary

{ key: dict[key] for key in dict.keys() if isinstance(key, int) } ...

How to display every key and value in a dictionary apart from one in python [duplicate]

python,dictionary,key,value

just this? not sure if I understand your question completely for i in dict1: if i != 'No': print i, dict1[i] output: >>> for i in dict1: ... if i != 'No': ... print i, dict1[i] ... Spirits 7 Bear 3 Wine 3 I am using the key "No" as...

python efficient group by

python,dictionary

l = [{'name': 'abc', 'id' : 1}, {'name': 'bc', 'id' : 1}, {'name': 'c', 'id' : 1}, {'name': 'bbc', 'id' : 2}] from collections import defaultdict from itertools import chain d = defaultdict(list) T = 2 for dct in l: d[dct["id"]].append(dct) print(list(chain.from_iterable(v for v in d.values() if len(v) > T)))...

Unmarshal JSON into a map in Go

json,dictionary,go

I believe that is because you have extra layer of indirection in your models. type JSONType struct { FirstSet map[string]string `json:"set1"` } Should suffice. if you specify map[string]string the object in json is recognized as that map. You created a struct to wrap it but a blob of json like...

Change Value of Class Instance Property inside Dictionary of Lists of Class Instances

c#,dictionary

To iterate over a dictionary you use the KeyValuePair<TKey,TValue> class. Since you have a list as your value you need to nest a loop within the iteration of the dictionary. Here's an example assuming myDictionary is of Dictionary<int, List<MyType>>: foreach(var keypair in myDictionary) { foreach(MyClass m in keypair.Value.Where(v => v.Property1.Equals("something"))...

Storing list element address into dictionary

python,list,dictionary

l = ['A', 'B', 'C'] d = {'A': {'value': 'a', 'index': 0}, 'B': {'value': 'b', 'index': 1}, 'C': {'value': 'c', 'index': 2}} l[d['B']['index']] 'B' # result! EDIT (see comment below) To create or update call this: from collections import defaultdict as DefaultDict def index_lookup(elements): result = DefaultDict(list) for index, key...

Returning Map> as a JSON from Spring. Map key elements do not parse into JSON format

json,spring,dictionary,jackson

EDIT: Maybe look at this first. Well, I had the same problem today and what I did was just creating a DTO: public class class MyDTO { public T key; public List<V> values; } and just convert it like that: @GET // etc. public List<MyDTO> getMyMap() { List<MyDTO> myDtoList =...

Using python dict imported from file in another python file

python,dictionary,python-3.4

There are two ways you can access variable TMP_DATA_FILE in file file1.py: import file1 var = 'a' print(file1.TMP_DATA_FILE[var]) or: from file1 import TMP_DATA_FILE var = 'a' print(TMP_DATA_FILE[var]) In both cases, file1.py must be in a directory contained in the python search path, or in the same directory as the file...

Overlay java maps, adding all keys

java,dictionary

If you are looking for alternative of addition.forEach((k1, v1) -> score1.compute(k1, (k2, v2) -> v2==null?v1:v1+v2)); then addition.forEach((k, v) -> score1.merge(k, v, (v1, v2) -> v1 + v2)); seems like improvement. So your code can also look like: Map<String, Integer> result = new HashMap<>(); score1.forEach((k, v) -> result.merge(k, v, (v1, v2)...

Replace a list item with the value of the item stored in dictionary in python

python,dictionary

There probably are lots of ways to do that, here is one more: map(b.get, a) or map(lambda x: b[x],a) Link to the map doc: https://docs.python.org/2/library/functions.html#map...

Proper way to initialize a C# dictionary with JavaScript json file?

javascript,c#,json,asp.net-mvc,dictionary

You should create a matching class to suit this JSON data model, and than Deserialize the data into the C# object. You should add the framework Json.NET Create C# Data model Deserialize the data from JSON to C# model. Example of DataModel: public class Child2 { public string id {...

Select / subset spatial data in R

r,dictionary,spatial

I'm going with the assumption you meant "to the right" since you said "Another solution might be to drawn a polygon around the Baltic Sea and only to select the points within this polygon" # your sample data pts <- read.table(text="lat long 59.979687 29.706236 60.136177 28.148186 59.331383 22.376234 57.699154 11.667305...

How do I check value in a nested dictionary in Python?

python,dictionary

def dictcheck(d, p, v): if len(p): if isinstance(d,dict) and p[0] in d: return dictcheck(d[p[0]], p[1:], v) else: return d == v You pass one dict d, one path of keys p, and the final value to check v. It will recursively go in the dicts and finally check if the...

List of type T to Dictionary

c#,list,dictionary

If you know the type in advance, I'd just use: var dictionary = list.Select(x => x.FirstName + ":" + x.UserId) .Concat(list.Select(x => x.LastName + ":" + x.UserId)) .ToDictionary(p => p, p => 0); There'll be one extra Concat call per additional property, but that shouldn't be too bad - again,...

Dictionary: Find same value using different but identical instances as keys [duplicate]

c#,dictionary

Yes, it is possible, as long as the corresponding Equals() method of your key returns true, and GetHashCode() returns the same integer value for what you call different but identical instances. In your example the result is 1.0 because String.Equals compares contents of the strings, not references (although, to be...

Dictionary int, myclass

list,c#-4.0,dictionary

You have List as TValue so: PersonelAtamaListesi.Add(0, new List<PersonelAtama>() { new PersonelAtama() { PersonelID = 1, YonetimTalepID = 2, durum = false }, new PersonelAtama() { PersonelID = 11, YonetimTalepID = 222, durum = true } }); ...

How can I implement a Zoom Panel with Java Swing libraries

java,swing,dictionary,scrollbar,zoom

I'm not 100% sure what the problem is, but I suspect that an issue is that you're not changing the preferred size of your image JPanel when the image changes size. If so, then a solution would be to override getPreferredSize() in the image displaying JPanel and return a dimension...

Python 3.4: List to Dictionary

python,list,python-3.x,dictionary

You can use unpacking operation within a dict comprehension : >>> my_dict={i:j for i,*j in [l[i:i+4] for i in range(0,len(l),4)]} >>> my_dict {'Non Recurring': ['-', '-', '-'], 'Total Other Income/Expenses Net': [33000, 41000, 39000], 'Selling General and Administrative': [6469000, 6384000, 6102000], 'Net Income From Continuing Ops': [4956000, 4659000, 4444000], 'Effect...

Get Keys from C# Dictionary

c#,dictionary

Certain operations are not allowed within foreach (emphasis mine): The foreach statement is used to iterate through the collection to get the information that you want, but can not be used to add or remove items from the source collection to avoid unpredictable side effects. If you are trying to...

Remove duplicate values from a defaultdict python

python,dictionary

I would suggest iterating on the items and for each value build a defaultdict incrementing the occurence. Then convert that indo your tuple list (with the item method) and drop that in the output dictionnary. b = {} for k,v in a.items(): d = defaultdict(int) for i in v: d[i]...

How to remove a value from a hashmap?

java,android,arrays,dictionary,arraylist

I assume you are referring to this line: aMap.remove(alunos); ... which is the only place where you are trying to remove from a HashMap. If that's the case, the problem is that you are not passing the right parameter value to aMap.remove(). That method expects you to pass a key...

How to use dictionary inside regex in python?

python,regex,dictionary

You can pass an arbitrary function, that takes a single match object and returns a string to replace it, as the repl for re.sub; for example: >>> import re >>> d = {'k': '23', 'v': '24'} >>> re.sub( r'p([kv])', lambda match: d[match.group()[1]], 'pvkkpkvkk', ) '24kk23vkk' ...

Subdivide nested dictionary, while applying percentage from values in Python

python,dictionary

You are getting the dictionary_with_temporal_distribution changed because in your code you are changing it - dictionary_with_temporal_distribution["{}".format(k)] = v * cap_medium_demand Instead you should consider creating a new dictionary at the start and maybe add elements to it as you continue processing and at the end return it. Also, instead of...

Python MySQLdb “INSERT INTO” Issue

python,mysql,dictionary,mysql-python

The mysqldb library only lets you substitute values, not tables: Python and MySQLdb: substitution of table resulting in syntax error...

Converting multi-line script output to dictionary using regex

python,regex,dictionary

You can use: (\w+)\s*=\s*\[?([^\n\]]+)\]? demo import re p = re.compile(ur'(\w+)\s*=\s*\[?([^\n\]]+)\]?', re.MULTILINE) test_str = u"host = g4u2680c.houston.example.com\n ipaddr = [16.208.16.72]\n VLAN = [352]\n Gateway= [16.208.16.1]\n Subnet = [255.255.248.0]\n Subnet = [255.255.248.0]\n Cluster= [g4u2679c g4u2680c g9u1484c g9u1485c]\n\nhost = g4u2680c.houston.example.com\n ipaddr = [16.208.16.72]\n VLAN = [352]\n Gateway= [16.208.16.1]\n Subnet = [255.255.248.0]\n Subnet =...

C++ How to add objects to maps and return reference to new created object inside map

c++,dictionary,shared-ptr

For your first question, you made House noncopyable (your copy constructor and copy assignment operator are private). The approach you are taking to insert requires you to make a pair first, the construction of which will copy the House you pass in. If you have access to a C++11 compiler,...