FAQ Database Discussion Community


How can I implement a Zoom Panel with Java Swing libraries

java,swing,dictionary,scrollbar,zoom
I've implemented a JFrame with Java Swing libraries to visualize a map. I'd like to realize a zoom function within this frame. This is the code of my JFrame: package components; import java.awt.BorderLayout; import java.awt.Container; import javax.swing.JFrame; import javax.swing.JScrollPane; public class MyFrame extends JFrame { private static final long serialVersionUID...

Compare dictionary key, values with nested list elements - Python

python,dictionary,nested-lists
Trying to match key, values in dictionaries with nested list elements dict = {'a':[1, 5], 'c':[7, 9], 'f':[10, 12], 'b':[15, 20]} list_A = [['a', '4'], ['a', '7'], ['b', '17'], ['b', 10], ['c', '7'], ['d', '7'], ['f', '11'], ['f', '12']] list_A_no_reps =['a', 'b', 'c', 'd', 'f'] I am trying to get...

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

python,dictionary
I'm new to Python and trying to figure out how to filter out all the non-string keys in a dictionary. I appreciate any help you can provide.

parse a dot seperated string into dictionary variable

python,string,dictionary
I have string values as, "a" "a.b" "b.c.d" How to convert them into python dictionary variables as, a a["b"] b["c"]["d"] The first part of the string (before dot) will become the dictionary name and the rest of the substrings will become the dictionary keys...

Sending a dictionary of javascript parameters to MVC Controller via JSON

javascript,c#,json,asp.net-mvc,dictionary
I'm using a third party library and cant really change the way it posts data to my MVC 5 controller. I cant figure out how to setup my model to receive the data. The json is a follows... { "expiration":"2015-06-14T21:02:52.969Z", "conditions":[ {"acl":"private"}, {"bucket":"anyoldbucket"}, {"Content-Type":"application/pdf"}, {"success_action_status":"200"}, {"key":"somekey"} ] } I tried...

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

python,file,dictionary
I'm trying to read a dictionary off a file and then make the string into a dictionary. I have this, with open("../resources/enemyStats.txt", "r") as stats: for line in stats: if self.kind in line: line = line.replace(self.kind + " ", "") line = dict(line) return line and the line in the...

Pygame 3D: How to and is it possible?

python,performance,dictionary,3d,pygame
So I want to program a 3d-mesh viewer in pygame, no other 3rd-party modules wanted (panda3d is perfect, but it's very complicated). My idea is: list_of_surfs = {'85 50':'70deg'} #the 85 50 and the dimensions of the #side/surf, and 70 deg of rotation to be able to see it, then...

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

function,swift,dictionary
Yes it's man vs compiler time and the compiler winning yet again! In the func getRecordNumber I am returning a Bool and a Dictionary func getRecordNumber(recordNumber: Int32) -> (isGot: Bool, dictLocations: Dictionary <String, Double>) ... return (isGot, dictLocations) However after I have called the func and question the Boolean isGot...

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
I want to find the points which the distant between points less than 3.For example, some points as follow, (220,221)(220,119)(220,220)(20,90)(220,222). I use (220,221) to find points.Then i can get (220,221)(220,119)(220,220)(220,222) I use (220,119) to find points.Then i can get (220,221)(220,119)(220,220) I have used Nested for loop to do that, but...

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

javascript,django,dictionary,apostrophe
I am trying to pass some dictionaries from a view to a javascript in my template. The data in view.py looks like: node_result = [{'y': 0.40750126710593004, 'x': 1}, {'y': 1.0, 'x': 0}, {'y': 0.10288900152052712, 'x': 0}] edge_result = [{'source': {'y': 0.40750126710593004, 'x': 1}, 'target': {'y': 0.40750126710593004, 'x': 1}}] In my...

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

python,dictionary
I have a list and a dictionary and I want to replace the list item with the value of the dictionary. A simplified version of my problem is as follows: #This is a list a=['dog', 'cat', 'cow'] #This is a dictionary b={'dog': 'barks', 'cat': 'meows', 'cow': 'moos' } Now list...

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

dictionary,f#,converter,record
I need to serialize arbitrary records into maps/dictionary. I imagine my end type look like this: type TabularData= array<Map<string, obj>> But I have problems in build a generic function that accept any record and turn them into Map....

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

c#,dictionary
I have a variable of type Dictionary<int, List<MyType>> where MyType is a class with several properties and methods. I am showing only two properties and no methods as they are irrelevant to the question. class MyType { private string property1; private double property2; public string Property1 { get { return...

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

json,spring,dictionary,jackson
I have a question connected to returning Map<T, List<V>> as a JSON response. I have a spring server which returns JSON objects, but now I'm exploring problem with returning Map in this format. I want return a Map<T, List<V>> from my server as a JSON and display it in the...

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

c#,dictionary
From the below code I always come to know whether any of the DatFiles is not in sync or not. But how to get which one? bool isNotinSync = DatFileListDictioanry.Any(t => IsThisDatFileNotInSync(t.Key)) // I want a key or Pair here! I know this can be achieved using a simple for...

Test if dict contained in dict

python,dictionary
Testing for equality works fine like this for python dicts: first = {"one":"un", "two":"deux", "three":"trois"} second = {"one":"un", "two":"deux", "three":"trois"} print(first == second) # Result: True But now my second dict contains some additional keys I want to ignore: first = {"one":"un", "two":"deux", "three":"trois"} second = {"one":"un", "two":"deux", "three":"trois", "foo":"bar"}...

Divide each python dictionary value by total value

python,dictionary
I have a = {'foo': 2, 'bar': 3, 'baz': 5 } Is there anyway I can get a = {'foo': 0.2, 'bar': 0.3, 'baz': 0.5 } in one line? Need to divide each value by total value... I just can't get it done.. :( Thank you so much!...

Trying to fill a SVG map from wordpress custom categories

wordpress,dictionary,svg
I've created a custom post_type (destinations) with a category (locations) to provide a tree structure for my SVG map: Continent/Country/Town Example locations: Europe/Germany/Berlin/POST Europe/Italiy/Sicily/POST North-Africa/Morocco/Marrakech/POST My plan was to fill the map by the country short codes like (DE for Germany, IT for Italia, LY for Libya (...). Here is...

Overlay java maps, adding all keys

java,dictionary
Does anyone know if there's a map structure or library that easily supports adding up the values of a map when combining two maps. HashMap<String, Integer> score1 = new HashMap<>(); HashMap<String, Integer> addition = new HashMap<>(); score1.put("Chicaco", 2); score1.put("New york", 1); addition.put("New york", 1); addition.put("Los Angeles", 1); Is there some...

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

pointers,dictionary,go
Supposedly maps are reference types in Go, so when returning them from functions, you don't need to pass as a pointer to the map in order for the changes to be visible outside the function body. But what if said map is returned from a method on a non-pointer struct?...

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

python,csv,dictionary
abc11 bvc ex 123 456 somestuffhere abc11 bvc ex 456 476 somestuffhere abc12 bvc ex 173 426 somestuffhere abc12 bvc ex 426 496 somestuffhere abc13 bvc ex 143 796 somestuffhere abc13 bvc ex 743 896 somestuffhere I am trying to put the above CSV file as a dictionary, {'abc11':['123','476'],'abc12':['173','496'],'abc13':['143','896']}. I...

Dictionary int, myclass

list,c#-4.0,dictionary
That's my class public class PersonelAtama { public int PersonelID { get; set; } public int YonetimTalepID { get; set; } public bool durum { get; set; } } I want to doDictionary<int,list<myclass>> Dictionary<int, List<PersonelAtama>> PersonelAtamaListesi = new Dictionary<int, List<PersonelAtama>>(); How to insert into the list PersonelAtamaListesi.Add How assignments are...

C++ Unordered Map

c++,dictionary,stl,unordered-map
I have a program in which I am using an iterator to get access to a value of a map entry . #include <iostream> #include <cstdio> #include <unordered_map> #include <utility> #include <algorithm> using namespace std; int main() { int a[]={1,2,4,7,9,3,3,55,66,88,11}; int k = 58; unordered_map<int,int> c; int i=0; for(auto x:...

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

c#,linq,sorting,dictionary
I have a SortedDictionary whose value is a List of objects. I want to sort the value(the list) of each key by a given property of the object. In the current situation, I need to sort the list first by objects's lastname, then by firstname. I tried LINQ and it...

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

python,json,dictionary
I have a json string and I want to know what its maximum depth is. By depth I mean the number of embedded keys. So if one key as 7 "children" and know other key had that many, the depth would be 8. Since the only types (I believe) that...

How to remove a value from a hashmap?

java,android,arrays,dictionary,arraylist
The thing is, I have an ExpandableListView with 2 groups, inside of each group I have some users and when I click on these users I get their ids and add to a HashMap of strings, now I'm trying to remove these ids when I click on them for the...

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

python,python-2.7,csv,dictionary
I have the following table generated in a text file,"fasta.txt" A C G T 0 0.195965417867 0.322766570605 0.35446685879 0.126801152738 A1 0.25 0.1875 0.3125 0.25 C1 0.25 0.475 0.225 0.05 G1 0.135135135135 0.243243243243 0.405405405405 0.216216216216 T1 0.142857142857 0.285714285714 0.285714285714 0.285714285714 A2 0.125 0.208333333333 0.625 0.0416666666667 C2 0.0833333333333 0.416666666667 0.305555555556 0.194444444444 G2...

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

python,dictionary,key,keyerror
I am programming a Graph class to handle pathing in a game. Graphs have one field, mapping, which is a dictionary that maps nodes to edges. In one of my functions, I have the following bit of code: for key in self.mapping: connected_edges = self.mapping[key] At one point in my...

Python3 create files from dictionary

file,python-3.x,dictionary
I have a dictionary in a function which is called searchInMyDict(dict) for example. The dictionary included in that function has for key a group name and has for value a list of gene's functions. the dictionary looks like : {"OG_1": ["gene's functionA, gene's functionB, gene's functionC"] "OG_2": ["gene's functionM, gene's...

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

c++,dictionary,shared-ptr
Bellow I provide the complete code for something really simple which I'm struggling with.. I need to create a map with strings and Objects... When requested, if the string is inside the map, I need to return a reference to one object inside the map When the string is not...

Conditional zip of two lists

python,dictionary
I'm trying to zip together two lists to create a new dictionary. List one is a list of column names represented as string, while list two is a list of variables. If the variable is empty (None) I don't want it or the corresponding column data (they share the same...

Equivalent of list.index() for an OrderedDict? [duplicate]

python,dictionary,ordereddictionary
This question already has an answer here: getting the key index in a Python OrderedDict? 3 answers Given that by its very nature, the items in an OrderedDict are ordered, one might expect it to have a function similar to the index function of lists. It does not. What...

c++ : double iteration through map

c++,dictionary,iterator
I would like to iterate through a map but the inner loop would just iterate through the upper part of the elements. With a vector it would look like that : for(auto element1 = myVector.begin() ; element1 != myVector.end() ; ++element1){ for(auto element2 = element1 + 1; element2 != myVector.end()...

C++ Create shared_ptr from Object

c++,c++11,dictionary,shared-ptr
So on my header file I have this declaration: typedef std::map<const std::string, std::shared_ptr<House> > myHouseMap; myHouseMap _myHouseMap; On my source file I can insert an object in my map like this: _myHouseMap.insert(std::pair<const std::string, std::shared_ptr<House>>("apartment", std::make_shared<House>("apartment"))); But now, I need to return the reference of the object. Therefore, I need to...

Inheritance: Set Values of Abstract Dictionary

c#,.net,inheritance,dictionary
I am currently working on a small project that includes an abstract baseclass of sorts, which defines some methods that require a dictionary. Yet the dicitionary is individual for each derived class. Therefore I defined the dictionary in my baseclass as follows: abstract internal Dictionary<string, column> columnNames { get; }...

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
Given a text file like so # Name_value_pair.txt name1 = value1 name2 = value2 name3 = "some value3" name4=value4 name5= name6 Is it possible to read that file, format it into a dictionary and print it out using python? I know how to open and read the files, but I...

Multi dimensional python dictionary [duplicate]

python,list,dictionary
This question already has an answer here: Generating python dict keys on the fly [duplicate] 3 answers I want to create a multi dimensional dictionary in python so that I can access them using the following notation: test['SYSTEM']['home']['GET'] test['SYSTEM']['home']['POST'] What would be the easiest way to set these values,...

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

python,dictionary,set,iteration,set-intersection
set_of_A_key and set_of_B_keyare two set of keys of dictionary dict_A and dict_B. I want operate over the dictionary values for the keys in the following three sets: (set_of_A_key & set_of_B_key), (set_of_A_key - set_of_B_key) and (set_of_B_key - set_of_A_key) What is the pythonic way to do this? This one is elegant with...

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

c++,dictionary,hash,unordered-map,comparison-operators
In order to quickly find coplanar entities in a bunch of planar entities in 3d space, I want to create a mapping from 3d planes to the set of entities lying in that plane (estimated max around ~1000 planes and ~100000 entities) I can create my own custom class to...

Python RuntimeError: maximum recursion depth exceeded in cmp

python,list,dictionary,recursion
I have a complex data structure that I'm trying to process. Explanation of the data structure: I have a dictionary of classes. The key is a name. The value is a class reference. The class contains two lists of dictionaries. Here's a simple example of my data structure: import scipy.stats...

Remove duplicate values from a defaultdict python

python,dictionary
I have a dictionary. a = {6323: [169635, 169635, 169635], 6326: [169634,169634,169634,169634,169634,169634,169638,169638,169638,169638], 6425: [169636,169636,169636,169639,169639,169640]} How do I remove the duplicate values for each key in dictionary a? And make the values become [value, occurrences]? The output should be b = {6323: [(169635, 3)], 6326: [(169634, 6), (19638, 4)], 6425: [(169636,...

Find last entry in a map

c++,qt,dictionary
I have a QMap<qreal,int> myMap; I need to find the largest key. Is this the only way ? I was hoping for something built in maybe. Is this good enough ? Isn't creating an iterator for a simple operation too much ? qreal maxkey() { QMap<qreal,int>::iterator it = myMap.end() -...

How to use dictionary inside regex in python?

python,regex,dictionary
Using a variable inside regex is easy and one way of achieving this is as: >>> z = '23' >>> re.sub(r'p[kv]', r"%s" %z, 'pvkkpkvkk') '23kk23vkk' But what if the replacement values are stored in a dictionary as: d = {'k':'23', 'v':'24'} and I want to use the dictionary to substitute...

Insert std::string and shared pointer to object in map

c++,c++11,dictionary,singleton
I'm using singleton design pattern (I can't use the copy constructor). I have a: Obj.hpp and Obj.cpp file House.hpp and House.cpp file The Obj class contains a map of Houses, where I can search for a house using a string. I can't even compile my Obj.cpp file, don't know why......

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

python,dictionary
I have an API that I call that returns a dictionary. Part of that dictionary is itself another dictionary. In that inside dictionary, there are some keys that might not exist, or they might. Those keys could reference another dictionary. To give an example, say I have the following dictionaries:...

Model to LazyMap

dictionary,groovy,deserialization
How do I convert/deserialize these models public class AccessCredentials { String userName = '' String password = '' LoginOptions loginOptions = new LoginOptions() } public class LoginOptions { String partnerId = '' String applicationId = '' } into a LazyMap like : [ userName : userName, password : password, loginOptions...

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

c#,algorithm,dictionary
I have two dictionaries Dictionary<string, object>. I need to find their intersection (I mean only their keys intersection) and A\B and B\A subtractions and make some actions to the objects (in fact my objects are EntityFramework entities and I have to mark their state as Modified, Added and Deleted respectively,...

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

python,python-2.7,dictionary,yield,yield-return
I have written a generating function that should return a dictionary. however when I try to print a field I get the following error print row2['SearchDate'] TypeError: 'generator' object has no attribute '__getitem__' This is my code from csv import DictReader import pandas as pd import numpy as np def...

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

python,dictionary,key,value
This question already has an answer here: Iterating over dictionaries using for loops in Python 6 answers dict1 = {"Bear":3,"Wine":3,"Spirits":7,"No":0} Here I have a dictionary and I want to display every key and value from Bear, Wine and spirits so it would look something like this: Bear 3 Wine...

Thread synchronisation for C++ map

c++,multithreading,dictionary,pthreads
I'm creating a multithreaded c++ program using pthread (c++98 standard). I have a std::map that multiple threads will access. The access will be adding and removing elements, using find, and also accessing elements using the [] operator. I understand that reading using the [] operator, or even modifying the elements...

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

python,list,dictionary
It is possible to map a dictionary key to a value that is a reference to a mutable object, such as a list. Such a list object can be changed by invoking a list method on the reference, and the changes will be reflected in the dictionary. This is discussed...

Get Keys from C# Dictionary

c#,dictionary
One would imagine this would be a pretty simple task, yet I'm getting a System.InvalidOperationException when I run this code: Dictionary<string, bool> TableExists = new Dictionary<string, bool>(); //... fill the dictionary foreach(string value in TableExists.Keys){/*Do something*/} It is supposed to iterate through the keys of the dictionary TableExists, but I...

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

java,dictionary,concurrentmodification
This question already has an answer here: iterating over and removing from a map 11 answers The following piece of code, while executed by a single thread, throws a ConcurrentModificationException on line 4: Map<String, String> map = new HashMap<String, String>(); map.put("key1", "value1"); map.put("key2", "value2"); for (String key : map.keySet())...

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

javascript,c#,json,asp.net-mvc,dictionary
I currently have a Web Socket between JavaScript and a server programmed in ASP.Net MVC 5. Does anyone know if there is a way I can insert json file into a C# dictionary when I create it? In JavaScript, I can pass data easily, but How can I initialize C#...

IDE doesn't recognize the method

c++,dictionary,hash,qt-creator,code-completion
I'm trying to acces the cityMethod() inside the class City. class City { void cityMethod() { } } So, I do: map<string,City> mymap; City c; mymap["Madrid"] = c; Now, when I do this: mymap["Madrid"].cityMethod(); Ok, it works. But the IDE(Qt) doesn't recognize the "cityMethod". Am I doing something wrong? Is...

Most common dictionary in array of dictionaries

arrays,swift,dictionary
I need to find the most common dictionary in an array of swift dictionaries. I tried using the following : func frequencies <S: SequenceType where S.Generator.Element: Hashable> (source: S) -> [(S.Generator.Element,Int)] { var frequency: [S.Generator.Element:Int] = [:] for x in source { frequency[x] = (frequency[x] ?? 0) + 1 }...

Using python dict imported from file in another python file

python,dictionary,python-3.4
I've the same issue as asked by the OP in How to import or include data structures (e.g. a dict) into a Python file from a separate file. However for some reason i'm unable to get it working. My setup is as follows: file1.py: TMP_DATA_FILE = {'a':'val1', 'b':'val2'} file2.py: from...

Pandas map to DataFrame from dictionary

python,dictionary,pandas
I am currently mapping and renaming various string values to columns in pandas via this function: df["fundbenchmark"] = df["name"].map(lambda x: "American Express" if "AXP" in x else "Apple" if "AAPL" in x else "Google" if "GOOG" in x else "") I will however do this for several columns and for...

python efficient group by

python,dictionary
I am looking for the most efficient way to extract items from a list of dictionaries.I have a list of about 5k dictionaries. I need to extract those records/items for which grouping by a particular field gives more than a threshold T number of records. For example, if T =...

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

c++,dictionary,constructor,instance
I have a class Object and a typedef: class Object { private: long int id; public: Object(void); ~Object(void) {}; long int get_id(void); }; typedef map<long int, Object> obj_map; And then I have this class App, which has an obj_map and object_counter: class App { public: static ALLEGRO_DISPLAY *display; static ALLEGRO_EVENT_QUEUE...

Create Dictionary from Penn Treebank Corpus sample from NLTK?

python,dictionary,nlp,nltk,corpus
I know that the Treebank corpus is already tagged, but unlike the Brown corpus, I can't figure out how to get a dictionary of tags. For instance, >>> from nltk.corpus import brown >>> wordcounts = nltk.ConditionalFreqDist(brown.tagged_words()) This doesn't work on the Treebank corpus?...

Unmarshal JSON into a map in Go

json,dictionary,go
I'm having trouble figuring out how to load a "subsection" of JSON file into a map element. Background: I'm trying to unmarshal a somewhat complicated configuration file which has a strict structure, so I assume it's preferable to unmarshal into a "static" structure rather than into an interface{}. Here's a...

Converting multi-line script output to dictionary using regex

python,regex,dictionary
I got the following script output: *************************************************** [g4u2680c]: searching for domains --------------------------------------------------- host = g4u2680c.houston.example.com ipaddr = [16.208.16.72] VLAN = [352] Gateway= [16.208.16.1] Subnet = [255.255.248.0] Subnet = [255.255.248.0] Cluster= [g4u2679c g4u2680c g9u1484c g9u1485c] host = g4u2680c.houston.example.com ipaddr = [16.208.16.72] VLAN = [352] Gateway= [16.208.16.1] Subnet = [255.255.248.0] Subnet =...

Determine location given a dictionary with lists inside of a list

python,dictionary
I'm new here and I need some help with some code I've been working on because I've gotten myself lost and am now just confused. First, I created a dictionary based on some help from this website. A sample of my dictionary looks like this: length = {'A': [(0,21), (30,41),...

Reach dictionary data within dictionary

swift,dictionary
How do I reach the second integer (key) within the following dictionary in Swift? And, while were at it, how would I reach the strings within the second dictionary? var activeCustomers = Dictionary<Int, Dictionary<Int, Dictionary<String, String>>>() I tried writing (for example) var test: Int = activeCustomers[1][1] but that did not...

Python do a lookup between 2 dictionaries

python-2.7,dictionary,lookup
I am trying to summarise two dictionaries as follows: mydict = {41100: 'Health Grant', 50050: 'Salaries', 50150: 'Salaries', 50300: 'Salaries'}; mytb = {'': '', 41100: -3,450,200.40, 50050: 1,918,593.96, 50150: 97.50, 50300: 8,570.80} My output should be: { 'Health Grant': -3450200.40, 'Salaries': 1927262.26 } Can you help with coding the for...

PHP / MySQL: How to store Select results in array

php,mysql,arrays,dictionary,key
I am new to PHP and MySQL and hope someone can help me with this. I have a MySql db with a table "TranslationsMain" and the following PHP query. This returns all the items from column "German" (incl. the corresponding ID) from the db table and works correctly so far....

Sorting a list with dictionaries, django

python,django,list,sorting,dictionary
myFrom two models in django i have created a list of dictionarys where each dictonary is a row in a table I show in the client. I would like to be able to sort this list for each of the different "columns". objdict = [] mydict = { 'thing1': model1.val1,...

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

python,dictionary
How can i prevent from adding a list into a list when using setdefault with a list type definition. output = dict() output.setdefault("key", []).append(["name", 1]) print output >>> {'key': [['name', 1]]} Desired output >>> {'key': ['name', 1]} ...

Python 3.4: List to Dictionary

python,list,python-3.x,dictionary
I have a string as follows : ['Total Revenue', 31821000, 30871000, 29904000, 'Cost of Revenue', 16447000, 16106000, 15685000, 'Gross Profit', 15374000, 14765000, 14219000, 'Research Development', 1770000, 1715000, 1634000, 'Selling General and Administrative', 6469000, 6384000, 6102000, 'Non Recurring', '-', '-', '-', 'Others', '-', '-', '-', 'Total Operating Expenses', '-', '-', '-',...

How to safely unwrap nil values in swift?

swift,dictionary
I am fairly new to swift and I am trying to understand how to deal with nil vars... I have two Dictionaries: var currencyname: NSDictionary = [ "CNY": "Chinese Yuan", "PLN": "Polish Zloty" "EUR": "Euro" ] var rawrates NSDictionary = [ "CNY": "1.34", "PLN": "1.456" ] I am combining them...

How to loop through multi-level json

python,json,dictionary
I would like to loop through each dictionary for Containers below and pull info out for each one as it relates to the top-level dictionary, my code below only loops through the last dictionary. How can I fix this to loop through all dictionaries? JSON: { "MetaData": {}, "SRData": {...

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

python,dictionary
This question already has an answer here: How can I sort a dictionary by key? 12 answers I am adding all the items of a list to a dictionary as keys equal to none. template_vars = headers[1:] kwargs = dict.fromkeys(template_vars) When I print the values of both variables in...

How to check bool inside of dictionary

arrays,swift,dictionary,random
I have the following piece of code: struct Dare { var theDare: [[String: AnyObject]] = [ ["dare": "Dare1", "darePerson": true], ["dare": "Dare2", "darePerson": false], ["dare": "Dare3", "darePerson": false], ["dare": "Dare4", "darePerson": true], ["dare": "Dare5", "darePerson": false] ] func randomDare() -> Dictionary<String, AnyObject> { return theDare[Int(arc4random_uniform(UInt32(theDare.count)))] } } How can i...

How to expand a string within a string in python?

python,string,dictionary,concatenation,list-comprehension
I have a string that looks like this: 1 | xxx | xxx | xxx | yyy*a*b*c | xxx I want to expand the yyy*a*b*c part so that the string looks like this: 1 | xxx | xxx | xxx | yyya | yyyb | yyyc | xxx I actually...

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

c++,templates,dictionary,stl,set
I have a specific search function. Because it's used on both std::set and std::map, it was duplicated in our code (not using template). I have to maintain those two functions, and I'd like to move them to a single function using a template (and then have only one search preocedure...

Select / subset spatial data in R

r,dictionary,spatial
I am working on a large data set with spatial data (lat/long). My data set contains some positions that I don´t want in my analysis (it makes the files to heavy to process in ArcMap- many Go of data). This is why I want to subset the relevant data for...

Creating a dictionary in a list from known variables [closed]

python,list,dictionary,nested-lists
I have some known values/variables a,b,c,d. I would like to use these variables to create a dictionary in a list. I did the following but it did not work: nestedlist['Name'] = a nestedlist['Address']['StreetNumber'] = b nestedlist['Address']['Zipcode']=c nestedlist['Email']=d I am getting the following error: Traceback (most recent call last): nestedlist['Address']['StreetNumber'] =...

Subdivide nested dictionary, while applying percentage from values in Python

python,dictionary
I want to subdivide a dictionary, while applying the values (which are percentages, to the value of another. I have those sets of data: {'C-STD-B&M-SUM': {datetime.date(2015, 5, 20): 0.21484699999999998, datetime.date(2015, 5, 21): 0.245074, datetime.date(2015, 5, 22): 0.27874} {'G-CAM-BAC-SUM': {datetime.date(2015, 5, 20): 0.13294399999999998, datetime.date(2015, 5, 21): 0.151648, datetime.date(2015, 5, 22): 0.17248,...

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

python,list,csv,dictionary
I've already searched for a solution to my problem but with no success. Part of the solution for my problem is here, but this does not solve it all. I have two lists of dictionaries like this - each dictionary is written to a csv file but I read the...

Compiler modifying a variable without adressing it

c#,variables,dictionary
In my program I found that when asssigning a variable to another, modifying the first one, also modifies the second. Example: using System; using System.Collections.Generic; using System.Windows.Forms; namespace Dict_test { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void TestButton_Click(object sender, EventArgs e) { Dictionary<string,...

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

python,dictionary
I am trying to create a nested dictionary. I have a list of tuples (called 'kinetic_parameters') which looks like this: ('New Model','v7','k1',0.1) ('New Model','v8','k2',0.2) ('New Model','v8','k3',0.3) I need the second column to be the outer key and the value to be another dictionary with inner key being the third column...

Swift Dictionary with Protocol Type as Key

ios,osx,swift,dictionary,protocols
short question here: I got a protocol protocol SCResourceModel {..} and a dictionary which shall use this protocol type as key: [SCResourceModel : String]. This obviously does not work, as a key in a dictionary has to conform to the protocol Hashable. Making my SCResourceModel inherit from Hashable or trying...

How to return random dictionary

arrays,swift,dictionary,random
Is it possible to return a dictionary this way? i guess it's just some syntax i got wrong. struct Dare { var theDare: [String: String, String: Bool;] = [ ["dare": "Dare1", "darePerson": true], ["dare": "Dare2", "darePerson": false], ["dare": "Dare3", "darePerson": false], ["dare": "Dare4", "darePerson": true], ["dare": "Dare5", "darePerson": false] ]...

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

python,dictionary
Suppose we have a list of dictionaries listD where each dictionary is quite deeply nested with more dictionaries. e.g.suppose that the first element of listD is: listD[0] = {"bar1":{"bar2":{"bar3":1234}}} Now I want to check if listD[i]["bar1"]["bar2"]["bar3"] == 1234 for all i. For the first element where i = 0, this...

Getting keyValuePair based on filtering of keys

c#,dictionary
I use myDictionary.Keys.Where to get a sequence but it returns just the keys (my predicate imposes conditions on keys). I would need to get the associated values as well and I am not sure how to do it easily, I am sure I miss some basic functionality..

Implementing a dictionary function to calculate the average of a list

python,list,dictionary
As always, I've attempted this for awhile before I proceed to ask a question on here. I know there are several attempts at answering this, but none really worked for what I needed. Here are the instructions: Implement the following three functions (you should use an appropriate looping construct to...

Python MySQLdb “INSERT INTO” Issue

python,mysql,dictionary,mysql-python
My code attempts to iterate through dictionary, "dbMap", and execute MySQL INSERT INTO statements based on the keys and values of dbMAP: for key in dbMap: try: cursor.execute("INSERT INTO '%s' (id, additional_details) VALUES (123, '%s')", (key, dbMap[key])) except UnicodeEncodeError: pass I get the following error when I run the above...

List of type T to Dictionary

c#,list,dictionary
I have an object List<T> and a keyfieldName of Type T i am trying to convert this List<T> to an Dictionary<string,double> for example if Type T is of type Person, i will be given keyfieldName ="UserId" ListItem1==> Person UserId 1 Firstname : "John" Lastname "Doe" ListItem2==> Person UserId 2 Firstname...

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

python,dictionary,enumerate
I got some help earlier today about how to obtain positional information from a dictionary using enumerate(). I will provide the code shortly. However, now that I've found this cool tool, I want to implement it in a different manner to obtain some more information from my dictionary. I have...

VBA dictionary data type

excel-vba,dictionary,key
Many sources, e.g. https://support.microsoft.com/en-us/kb/187234, claim the key of a dictionary can be of many data types beyond string. However, when I tried integers and dates as keys, it fails. Can someone explain? I tried the answer of @Tim Williams below, it works. What I had before was Private Sub trial()...

Create huge dictionary

c#,arrays,dictionary
In my quest to the primes, I've already asked this question : Can't create huge arrays which lead me to create my own class of fake arrays based on a dictionary of arrays... : private Dictionary<int, Array> arrays = new Dictionary<int, Array>(); I can know create fake arrays of a...

Exception when attempting to modify Dictionary

c#,exception,dictionary
I was creating a Dictionary to manage Threads and I ran into this exception when I attempt to clear dead threads after adding some Threads into the dictionary. using System; using System.Collections.Generic; using System.Threading; namespace SysCat { public class ThreadManager { public static readonly ThreadManager GlobalThreadManager = new ThreadManager( );...

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

python,dictionary
I have one dictionary with key and value. Key is row name and values is the last seat number. I would like to find the row number based on the input value. seats_dict={'A':10,'B':'20':'C':30} Input: seat_num =16 Output: Should be 'B' Is there any function to identity this in python?...

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

python,dictionary
I have a dictionary that contains some values color=[black, white,....] a have a lot of strings (in one array) that contains a lot of this colors and I need to replace them with the letter C. So for example "this is a phrase and it contains Blue" must be "this...

Python remove method mute the dictionary keys

list,dictionary
I want to use a dictionary representing a directed graph with a certain number of nodes (num) and with all possible edges (output). Examples: if num = 1, output: {0: set([])} if num = 2, output: {0: set([1]), 1: set([0])} if num = 3, output: {0: set([1,2]), 1: set([0,2]), 2:...

Storing list element address into dictionary

python,list,dictionary
I have 2 data structures - list, and dictionary. List holds a bunch of keys. Dictionary has those same keys. As for the value of each key, I want to store the address of corresponding element in the list. What would this achieve: For a key, I would lookup the...

Add to value in Dictionary

c#,dictionary
I have a Dictionary<Product, int> Inventory which holds the inventory for the products that are in the shop. How do I get the value that corresponds with the Product and add 1 to it? It is also possible that the Product isn't in the dictionary....

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

c#,dictionary
This question already has an answer here: Using an object as a generic Dictionary key in .net 3 answers Is it possible to achive the following behaviour from a dictionary in a convenient way: Dictionary<MyObject, double> d = new Dictionary<MyObject, double> MyObject foo = new MyObject("foo"); d[foo] = 1.0;...

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

python,loops,dictionary
I have read two files from which I created dictionaries with IDs and their corresponding sequences as keys and values, respectively. I am trying to find the key/value pairs that exist in both dictionaries and to create a new one containing only these matching ones. Each dictionary has a couple...