Is there a Python equivalent for Ruby characters?

Is there a Python equivalent for Ruby characters?

  • If so, what is it?

  • If not, are we stuck using strings like our keys are only in dictionaries?

+59
python dictionary ruby symbols language-comparisons
Sep 18 '10 at 21:14
source share
5 answers

No, python has no character type.

However, string literals are interned by default, and other strings can be interned using the intern function. Therefore, the use of string literals as keys in dictionaries is no less effective than the use of symbols in a ruby.

+66
Sep 18 '10 at 21:19
source share
β€” -

As others have said, in Python there is no character, but strings work well.

To avoid quoting strings as keys, use the dict () constructor syntax:

 d = dict( a = 1, b = 2, c = "Hello there", ) 
+14
Sep 18 '10 at 23:21
source share
  • No, there is no equivalent.
  • No, you can use each hashed object as a dictionary key.
+6
Sep 18 '10 at 21:18
source share

Also for those interested: the characters in Ruby when used in a hash are very similar to empty objects in python. For example, you can do:

 some_var = object() 

and then set the dictionary key as some_var:

 some_dict = { some_var : 'some value' } 

and then do a standard search:

 some_dict[some_var] 

However, since sepp2k noted that there is no performance benefit. In fact, I did a quick test and added little to the performance increase:

 a, b, c, d, e = [object() for _ in range(5)] dict_symbols = {a : 'a', b : 'b', c : 'c', d : 'd', e : 'e'} dict_strings = {'a' : 'a', 'b' : 'b', 'c' : 'c', 'd' : 'd', 'e' : 'e'} def run_symbols(): for key in dict_symbols.keys(): dict_symbols[key] def run_strings(): for key in dict_strings.keys(): dict_strings[key] 

Speed ​​tested in ipython:

 In [3]: %timeit run_symbols 10000000 loops, best of 3: 33.2 ns per loop In [4]: %timeit run_strings 10000000 loops, best of 3: 28.3 ns per loop 

So, in my case, β€œcharacters” are slower! (for funny numbers, inaccurate). However, it should be noted that there are probably memory advantages for this. Unless you care that key type objects are smaller than strings.

 import sys sys.getsizeof('some_var') # 45 some_var = object() sys.getsizeof(some_var) # 0 

Although this raises the question of how python handles the memory of the variable name some_var.

+5
Apr 22 '14 at 6:43
source share

Not as a first class type, but there is https://pypi.python.org/pypi/SymbolType .

+2
Jul 20 '13 at 22:11
source share



All Articles