Case insensitive dictionary

case insensitive dictionary python
c# todictionary case-insensitive
iequalitycomparer case-insensitive
how to make dictionary key case insensitive python
json.net case insensitive dictionary
c# dictionary
dictionary get ignore case
linq to dictionary ignore case

I'd like my dictionary to be case insensitive.

I have this example code:

text = "practice changing the color"

words = {'color': 'colour',
        'practice': 'practise'}

def replace(words,text):

    keys = words.keys()

    for i in keys:
        text= text.replace(i ,words[i])
    return  text

text = replace(words,text)

print text

Output = practise changing the colour

I'd like another string, "practice changing the Color", (where Color starts with a capital) to also give the same output.

I believe there is a general way to convert to lowercase using mydictionary[key.lower()] but I'm not sure how to best integrate this into my existing code. (If this would be a reasonable, simple approach anyway).

If I understand you correctly and you want a way to key dictionaries in a non case-sensitive fashion, one way would be to subclass dict and overload the setter / getter:

class CaseInsensitiveDict(dict):
    def __setitem__(self, key, value):
        super(CaseInsensitiveDict, self).__setitem__(key.lower(), value)

    def __getitem__(self, key):
        return super(CaseInsensitiveDict, self).__getitem__(key.lower())

Case insensitive access for generic dictionary, There's no way to specify a StringComparer at the point where you try to get a value. If you think about it, "foo".GetHashCode() and "FOO". To compare, ignoring case, use the case-insensitive Dictionary. While declaring a Dictionary, set the following property to get case-insensitive Dictionary − StringComparer.OrdinalIgnoreCase Add the property like this − Dictionary <string, int> dict = new Dictionary <string, int> (StringComparer.OrdinalIgnoreCase); Here is the complete code −

Make a case-insensitive dictionary in C#, The following code builds a dictionary that is case-insensitive so it treats “Rod Stephens” and “rod stephens” as the same key value. If you think about it, "foo".GetHashCode() and "FOO".GetHashCode() are totally different so there's no reasonable way you could implement a case-insensitive get on a case-sensitive hash map. You can, however, create a case-insensitive dictionary in the first place using:-

Just for the record. I found an awesome impementation on Requests:

https://github.com/kennethreitz/requests/blob/v1.2.3/requests/structures.py#L37

Case-insensitive Dictionary in C#, To compare, ignoring case, use the case-insensitive Dictionary. While declaring a Dictionary, set the following property to get case-insensitive  Update: As Ceser Perez mentioned in comments, there is a far better way available to create a case insensitive dictionary in C# using one of available overload. I would recommend you to use that overload instead of the method I mentioned below. so return(); Create a new class that inherits the existing dictionary.

In my particular instance, I needed a case insensitive lookup, however, I did not want to modify the original case of the key. For example:

>>> d = {}
>>> d['MyConfig'] = 'value'
>>> d['myconfig'] = 'new_value'
>>> d
{'MyConfig': 'new_value'}

You can see that the dictionary still has the original key, however it is accessible case-insensitively. Here's a simple solution:

class CaseInsensitiveKey(object):
    def __init__(self, key):
        self.key = key
    def __hash__(self):
        return hash(self.key.lower())
    def __eq__(self, other):
        return self.key.lower() == other.key.lower()
    def __str__(self):
        return self.key

The __hash__ and __eq__ overrides are required for both getting and setting entries in the dictionary. This is creating keys that hash to the same position in the dictionary if they are case-insensitively equal.

Now either create a custom dictionary that initializes a CaseInsensitiveKey using the provided key:

class CaseInsensitiveDict(dict):
    def __setitem__(self, key, value):
        key = CaseInsensitiveKey(key)
        super(CaseInsensitiveDict, self).__setitem__(key, value)
    def __getitem__(self, key):
        key = CaseInsensitiveKey(key)
        return super(CaseInsensitiveDict, self).__getitem__(key)

or simply make sure to always pass an instance of CaseInsensitiveKey as the key when using the dictionary.

C# Dictionary and case insensitive ContainsKey checking , The default constructor of C# Dictionary class constructs a Dictionary object, in which the keys are case sensitive. So when you insert data pairs  The following code builds a dictionary that is case-insensitive so it treats “Rod Stephens” and “rod stephens” as the same key value. This example builds the dictionary and then tests it by adding and searching for a bunch of test items. It then builds a regular case-sensitive dictionary and performs the same tests.

Would you consider using string.lower() on your inputs and using a fully lowercase dictionary? It's a bit of a hacky solution, but it works

C# Case-Insensitive Dictionary, This C# program uses a case-insensitive Dictionary. It uses StringComparer.​OrdinalIgnoreCase. | TheDeveloperBlog.com. json.net – case insensitive dictionary JSON.NET can of course deserialize a dictionary out of the box but yesterday I needed to change the way the dictionary is created during deserialization. I needed the dictionary to be case insensitive when comparing string-keys, which means that the dictionary needs to be created with the StringComparer

Case-Insensitive Dictionary in ASP.NET C#, How to declare a case-insensitive dictionary (using string as keys) without changing your existing code in ASP.NET C# (for ASP.NET MVC, . All Dictionaries are case-sensisitive. But you can use the case-insensitive string comparers provided by the StringComparer class to create dictionaries with case-insensitive string keys. Check it from ideone. answered Dec 21 '12 at 18:32

StringDictionary.ContainsKey(String) Method (System.Collections , Determines if the StringDictionary contains a specific key. The key is handled in a case-insensitive manner; it is translated to lowercase before it is used. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. c# Dictionary: making the Key case-insensitive

c#, dictionary-trygetvalue-case-insensitive.aspx. <%@ Page Language="C#" AutoEventWireup="true"%> <!DOCTYPE html> <script runat="server"> protected void  Case-sensitive definition is - requiring correct input of uppercase and lowercase letters. How to use case-sensitive in a sentence.

Comments
  • See PEP-455: this is scheduled for standard library inclusion in Python 3.5 (as collections.TransformDict, provided the transform is str.casefold or similar)
  • @NickT This PEP has been rejected. python.org/dev/peps/pep-0455/#rejection
  • Isn't there a special builtin that is called for 'in' as well?
  • Here is a complete list of methods that may need overloading: setitem, getitem, contains, get, has_key, pop, setdefault, and update. init and fromkeys should also possibly be overloaded to make sure the dictionary is initialized properly. Maybe I'm wrong and somewhere Python promises that get, hash_key, pop, setdefault, update and init will be implemented in terms of getitem, setitem and contains if they've been overloaded, but I don't think so.
  • added __contains__, get, and has_key to the answer since I ended up coding them :)
  • This solution is very limited as it doesn't work for a lot of common uses of dict. Don't use it in your code - it will break all but the simplest uses. Apparently @MichaelMerchant attempted to add the missing stuff, but moderation dissaproved the changes (same thing happened to me). I added a new answer which should be usable as a drop-in dict replacement here.
  • Like the others said, setdefault as example is broken! "descriptor 'setdefault' requires a 'dict' object but received a 'str'"
  • This is great, but there is one minor problem. The super definition of update is update(self, E=None, **F), meaning E is optional. You've re-defined it to make E required. Add in the =None and this will be perfect.
  • Nice catch @NickWilliams. Thanks!
  • Python is easy, they said. Python is fun, they said.
  • @rr-. To be totally fair, imagine doing this in say C.
  • In python 3 the abstract type basestring was removed. str can be used as a replacement.
  • from requests.structures import CaseInsensitiveDict
  • That might work, but if what you need is just a Case Insensitive Dict, it's silly to add requests as a dependency just for that.