dictionary,equality,julia-lang , Julia's dictionary method `haskey` returning false when key is present

Julia's dictionary method `haskey` returning false when key is present


Tag: dictionary,equality,julia-lang

I am new to Julia and I am not sure why the last line evaluates to false:

type Point{T}

D = [Point(1.,2.) => 42]
haskey(D, Point(1., 2.))  #False!

Clearly the key exists so what's going on here!?


If I don't use a class Point, it works fine:

D = [(1.,2.) => 42]
haskey(D, (1., 2.))  #True!

Can we not use classes for dictionary key types?


But look at this:

type Point{T}
P = Point(1., 2.)
D = [P => 42]
haskey(D, P)

evaluates to true.

It does work if you use the same object, but it does not work if you use 2 objects with the same field values. Note that objects defined using type are mutable, so even after you used a Point as a key, you could have still changed the values of its fields without the dictionary knowing. The dictionary needs to hash on something that cannot change, like a type-object's identity, and not it's field values of the moment. Since tuples are immutable their values can be safely used as keys. You could also use

immutable Point{T}


Model to LazyMap

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...

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

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...

Get Keys from 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...

Python RuntimeError: maximum recursion depth exceeded in cmp

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...

Template C++: How to access iterator value for both std::map and std::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...

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

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....

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

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;...

How to return random dictionary

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] ]...

Storing list element address into 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...

C++ 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:...

Reach dictionary data within 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...

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

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 to remove a value from a hashmap?

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 do I check value in a nested dictionary in Python?

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...

Create Dictionary from Penn Treebank Corpus sample from NLTK?

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?...

List of type T to 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...

Compare dictionary key, values with nested list elements - Python

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...

Using python dict imported from file in another python file

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...

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

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...

Unmarshal JSON into a map in 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...

parse a dot seperated string into dictionary variable

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...

Python do a lookup between 2 dictionaries

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...

Swift Dictionary with Protocol Type as Key

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...

VBA dictionary data type

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()...

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

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...

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

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...

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

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...

Trying to fill a SVG map from wordpress custom categories

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...

How to check bool inside of dictionary

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...

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

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...

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

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...

IDE doesn't recognize the method

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...

PHP / MySQL: How to store Select results in array

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....

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

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]} ...

Pygame 3D: How to and is it possible?

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...

Python 3.4: List to 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', '-', '-', '-',...

Thread synchronisation for C++ map

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...

Overlay java maps, adding all keys

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...

Python3 create files from 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...

Sorting a list with dictionaries, django

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,...

Implementing a dictionary function to calculate the average of a list

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...

Select / subset spatial data in R

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...

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

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?...

How to find exact place for given value in 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?...

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

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...

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

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:...

Compiler modifying a variable without adressing it

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,...

Inheritance: Set Values of Abstract 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; }...

Remove duplicate values from a defaultdict python

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,...

c++ : double iteration through map

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()...