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

Categories : Dotnet

Complex Python JSON object to custom dictionary conversion
Sometimes when operating on nested structures using recursive functions, its easier to think in terms of a walking function and an operation function. So we want to target all the dicts contained in the json structure and perform a transformation operation on them. Transforming a structure in-place, instead of recreating a new one, is significantly easier when dealing with nests. The more difficult approach of constructing nested dicts from that json structure involves being able to address the specific json elements, place them at correct depth and branch of the new structure; this involves two parallel walking operations. One thing to be mindful of though, is modifying the nested structure while walking across it as a transformation operation may change a list that the walking function

Categories : Python

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

Categories : Python

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

Categories : Python

Add Mutable Dictionary to a Mutable Dictionary for conversion to JSON
A. NSMutableDictionary does not copy the values (only the keys). Therefore you add the same dictionary two times and change both (= the one) when removing objects and so on. Beside this in your sample JSON the numbers looks like strings not like numbers. I think, that this is a typo. B. Adding modern Objective-C for better readability it should look like this: NSDictionary *basicDictionary = @{ @"menuHeight" : @46, @"menuMethod" : "editText", @"menuOption : @1 } NSDictionary *proDictionary = @{ @"menuHeight" : @96, @"menuMethod" : "sendText", @"menuOption : @1 } NSDictionary *nestedSections = @{ @"Pro" : proDictionary, @"Basic" : basicDictionary };

Categories : Xcode

Javascript dictionary of syntax (standard functions, objects, methods, and keywords)
The Mozilla Developer Network is a great place for JS documentation. They have a greatly written wiki with thousands of articles for almostly everything, even some documentation for the upcoming ECMAScript 6. See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/ https://developer.mozilla.org/en-US/docs/DOM/DOM_Reference

Categories : Javascript

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

Categories : Python

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

Categories : Asp Net

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

Categories : Python

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

Categories : Python

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

Categories : Python

Add word to user dictionary and retrieve them back from dictionary
I managed to find solution of my question by my own....answering this question in the hope that it might help someone as a reference for the same kind of issue: public class HomeActivity extends Fragment implements TextWatcher { String itemClientName[] = {}; ArrayAdapter<String> clientNameAdapter; ArrayList<String> clientNameList = new ArrayList<String>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); AutoCompleteTextView et_client_name = (AutoCompleteTextView) findViewById(R.id.et_client_name); getFromDictionary(); suggestClientName(); et_client_name.addTextChangedListener(this); } public void getFrom

Categories : Android

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

Categories : C#

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

Categories : C#

Python3 replace using dictionary
You are first replacing all As with Ts before then replacing all Ts with As again (including those you just replaced As with!): >>> string = 'ACGTACG' >>> string.replace('A', 'T') 'TCGTTCG' >>> string.replace('A', 'T').replace('T', 'A') 'ACGAACG' Use a translation map instead, fed to str.translate(): transmap = {ord('A'): 'T', ord('C'): 'G', ord('T'): 'A', ord('G'): 'C'} return string.translate(transmap) The str.translate() method requires a dictionary mapping codepoints (integers) to replacement characters (either a single character or a codepoint), or None (to delete the codepoint from the input string). The ord() function gives us those codepoints for the given 'from' letters. This looks up characters in string, one by one in C code, in the translation

Categories : Python

How to use str.replace() with a dictionary of replacements? Python
You are looking for unicode.translate() instead. It takes a mapping of unicode ordinals (integer numbers) and the values should be ordinals too, or unicode strings, or None to signal to delete that character: replacements = {ord(k): ord(v) for k, v in replacements.iteritems()} sentence = sentence.translate(replacements) Demo: >>> replacements = {ord(k): ord(v) for k, v in replacements.iteritems()} >>> replacements {8216: 39, 8217: 39, 8212: 45, 8221: 34, 8220: 34} >>> u'u2019Hello world! u2014 You rock!u2018'.translate(replacements) u"'Hello world! - You rock!'"

Categories : Python

Replace string based on a dictionary
You are saving only the last replace to the aminoacidos variable. I changed your code to replace the rna string and set it to rna. It should work. def converteRNAmParaAminoacidos(rna): dicionario = {'uuu':'F', 'uuc':'F','uua':'L', 'uug':'L', 'cuu':'L', 'cuc':'L', 'cua':'L', 'cug':'L', 'auu':'I', 'auc':'I', 'aua':'I', 'aug':'M', 'guu':'V', 'guc':'V', 'gua':'V', 'gug':'V', 'ucu':'S', 'ucc':'S', 'uca':'S', 'ucg':'S', 'ccu':'P', 'ccc':'P', 'cca':'P', 'ccg':'P', 'acu':'T', 'acc':'T', 'aca':'T', 'acg':'T', 'gcu':'A', 'gcu':'A', 'gcc':'A', 'gca':'A', 'gcg':'A', 'uau':'T', 'uac':'T', 'uaa':'*', 'uag':'*', 'cau':'H', 'cac':'H', 'caa':'G', 'cag':'G', 'aau':'N', 'aac':'N', 'aaa':'K', 'aag':'K', 'gau':'D', 'gac':'D', 'gaa':'E', 'gag':'E', 'ugu':'C', 'ugc':'C', 'uga':'*', 'ugg':'W', 'cgu':'R', 'cg

Categories : Python

Efficient dictionary inversion on dictionary like file
I would suggest the following 3 pass solution: Iterate over your original dictionary file once, adding a val, key line to your output file for each val as you go. Sort the output file from step 1 using the unix sort command or some other fast sorting program. If there is a possibility that step 1 produced duplicates that need to be removed, iterate over the output file from 2 and remove duplicates as you write your final output file. Because the output file from 2 is sorted, you need only one pass and minimal memory to do this.

Categories : Python

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

Categories : Python

Bind ComboBox to Dictionary and the Selected to the Dictionary Key
Answer based on comment link from Anatoliy <ComboBox Grid.Row="2" Grid.Column="3" DataContext="{Binding RelativeSource={RelativeSource AncestorType=Page}}" ItemsSource="{Binding Path=DLchars}" PresentationTraceSources.TraceLevel="High" VerticalAlignment="Center" SelectedValuePath="Key" SelectedValue="{Binding Path=EOL}"> <ComboBox.ItemTemplate> <DataTemplate> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="25"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <TextBlock Grid.Column="0" Text="{Binding Path=Key}" />

Categories : Dotnet

Most efficient way to populate dictionary keys with dictionary
I believe you're looking for copy.deepcopy(). friends = { "John": copy.deepcopy(places), "Carter": copy.deepcopy(places), "Bill": copy.deepcopy(places), }

Categories : Python

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

Categories : Python

Python Spell Check Replace in Dictionary
Without any sample input to test, it seems you want something like this: newList=[] for line in separate: for word in line: if word in wordList: newList.append(word) elif word in d: newlist.append(d[word]) else: # Skip the word? pass return newList BONUS: If you want to iterate over all keys and values in a dict, you can do it like this: for key, value in d.iteritems(): newList=newList.replace(key, value)

Categories : Python

How to replace elements in a list using dictionary lookup
If all values are unique then you should reverse the dict first to get an efficient solution: >>> subs = { ... "Houston": "HOU", ... "L.A. Clippers": "LAC", ... ... } >>> rev_subs = { v:k for k,v in subs.iteritems()} >>> [rev_subs.get(item,item) for item in my_lst] ['L.A. Clippers', 'Houston', '03/03 06:11 PM', '2.13', '1.80', '03/03 03:42 PM'] If you're only trying to updated selected indexes, then try: indexes = [0, 1] for ind in indexes: val = my_lst[ind] my_lst[ind] = rev_subs.get(val, val)

Categories : Python

Json Data converted to Json string but not in Json Dictionary
Well there is no error in what you are doing and the log says clearly you are getting a NSDictionary, and If you try to log an NSDictionary it is obvious you get a json string response.See this line NSLog(@" dicjson : %@ json string : %@ error : %@",dicJsonRequest,strJsonRequest,convertError.localizedDescription); Here the NDDictionary contains the value correctly since the log shows dicjson : { email = "test@test.com"; name = abcd; password = test; } So you have a valid dictionary in hand.Just do the remaining coding

Categories : Iphone

python using a dictionary to replace characters in a list of strings
progression is a list. To access content from it, you need to use the index value, which is an integer, and not a string, hence the error. You probably want: for i, j in enumerate(words): words[i] = clues.get(j) What enumerate does is loops through the list of words, where i is the index value and j is the content. .get() is similar to dict['key'], but if the key is not found it returns None instead of raising an error. Then words[i] modifies the list with the index number of the word

Categories : Python

How to create Android custom keyboard OR write custom Dictionary
Refer this link, http://www.fampennings.nl/maarten/android/09keyboard/index.htm. Hope this will help you

Categories : Java

Extracting key and values in dictionary with in dictionary in C#
Absolutely no clue what you are trying to do but Given Dictionary<string, Dictionary<string,IEnumerable<AGString>>> Data = new Dictionary<string, Dictionary<string,IEnumerable<AGString>>>(); foreach(string k1 in Data.Keys) { foreach(string k2 in Data[k1].Keys) { foreach(AGString ag in Data[k1][k2]) { // do something with k1, k2 and ag } } }

Categories : C#

A dictionary for each variable or a dictionary for all variables?
I would prefer the second solution since you can do: if platform == windows: vars = win_vars elif platform == posix: vars = lin_vars And then later in you application you don't have to deal with de branching. Just use the vars variable. Note: I haven't specified the way to check for the platform since there are multiple ways depending on what you need. You can either check the sys.platform, use the platform module or check if posix, nt... is in sys.builtin_module_names.

Categories : Python

dictionary of dictionary key to multi index
a dict of frames forms a panel, to_frame transmutes to a 2-level index, you want an additional level which concat forms when passed a dict In theory you could do something like a recursive reduction if you needed more levels, but that blows up the brain. To get your exact output, you can do a sortlevel. In [36]: concat( dict([ (k,Panel(v).to_frame()) for k,v in t.items() ]) , names= ['level']) Out[36]: 1 2 level major minor a 0 0 1 5 1 2 6 1 0 3 7 1 4 8 b 0 0 1 5 1 2 6 1 0 3 7 1 4 8

Categories : Python

How to convert a dictionary pair.value to a dictionary in C#?
Assuming tset in your array is a typo and it actually is test, you can use concerete classes .... string json = @"{""dest"":[ { ""mode"": ""1"", ""test"":""test1,test,test2""},{ ""mode"": ""2"", ""test"": ""test3"" }]}"; var obj = new JavaScriptSerializer().Deserialize<MyObject>(json); public class Dest { public string mode { get; set; } public string test { get; set; } } public class MyObject { public List<Dest> dest { get; set; } }

Categories : C#

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

Categories : Python

Python : Match a dictionary value with another dictionary key
third_dict = {k: tr[v[0]] for k, v in scnd_dict.iteritems() if v[0] in tr} This tr = defaultdict(list) is a waste of time if you are just rebinding tr on the next line. Likewise for scnd_dict. It's a better idea to make all the values of tr lists - even if they only have one item. It will mean less special cases to worry about later on.

Categories : Python

How to make a fast dictionary that contains another dictionary?
Don't be afraid of collisions, use cryptographic hash. But choose a fast one. 256 bit collision is MUCH less probable than hardware error. Sun used it to deduplicate blocks in ZFS. ZFS uses SHA256. Probably you can use less secure hash. If it takes $1000000 to find one collision hash isn't secure but one collision don't seem to drop your performance. Many collisions would cost many $1000000. You can use something like (unordered) multimap<SHA, T> to deal with collisions. By the way, ANY hash table suffer from collisions (or takes too many memory), so ordered map (rbtree in gcc) or btree_map has better guaranteed time. Also hash table can be DOSed via hash collisions. Probably a secret salt can solve this problem. It is due to table size is much less than number of possible hashes.

Categories : C++

How to check if a dictionary is in another dictionary in python
You're checking if the actual list is in there, not the tuple. Here, you can use all(): all(i in a3.f.items() for i in L[0].f.items()) Or even set notation: >>> set(L[0].f.items()) & set(a3.f.items())) == set(L[0].f.items()) True # Note that without the bool call this returns set([('a', 1)]), which can # be useful if you have more than one sublist tuples.

Categories : Python

How add dictionary inside another dictionary using loops?
Just from the top of my head (if I understood you correctly): maindict = dict([x, mydict] for x in range(5)) Will give you maindict: {0: <mydict>, 1: <mydict>, ... , 4: <mydict>}

Categories : Python

Getting Dictionary From JSON
Just try to Either NSDictionary *dict = [str JSONValue]; NSLog(@"%@", dict); OR NSError *error; NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseCust options:nil error:&error]; NSLog(@"%@", dict);

Categories : IOS

Using a dictionary to replace column values on given index numbers on a pandas dataframe
You are looking for DataFrame.update. The only twist in your case is that you specify the updates as a dictionary of rows, whereas a DataFrame is usually built from a dictionary of columns. The orient keyword can handle that. In [25]: df_test Out[25]: a b c one 1 NaN NaN two 2 NaN NaN three 8 5 4 In [26]: row_replacements = { 'one': [3.1, 2.2], 'two' : [8.8, 4.4] } In [27]: df_update = DataFrame.from_dict(row_replacements, orient='index') In [28]: df_update.columns = ['b', 'c'] In [29]: df_test.update(df_update) In [30]: df_test Out[30]: a b c one 1 3.1 2.2 two 2 8.8 4.4 three 8 5.0 4.0 from_dict is a specific DataFrame constructor that gives us the orient keyword, not available if you just say DataFrame(...). For reasons I don't kn

Categories : Python

Access the Dictionary From Json URL
I'm using 3rd party library called AFNetworking to make JSON requests and parse the response. Here's an example: AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:@"http://yoursite.com"]; NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" path:@"blah/path" parameters:@{@"jsonKey":@"jsonValue"}]; AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *res, id json) { // Use the json here json[@"ca

Categories : IOS

JSON to dictionary in JavaScript?
You could write a javascript function to get an employee by id from a list of employees: function getEmployee(id, employees) { for (var i = 0; i < employees.length; i++) { var employee = employees[i]; if (employee.id === id) { return employee; } } return null; } and then use this function on the response you got from the server after parsing the JSON string back to a javascript object: var json = 'the JSON string you got from the server'; var obj = JSON.parse(json); var employees = obj.employees; var employee = getEmployee(34, employees); if (employee != null) { alert(employee.name); }

Categories : Javascript



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