ordereddictionary

Python select ith element in OrderedDict

只愿长相守 提交于 2019-12-04 22:37:18
I have a snippet of code which orders a dictionary alphabetically. Is there a way to select the ith key in the ordered dictionary and return its corresponding value? i.e. import collections initial = dict(a=1, b=2, c=2, d=1, e=3) ordered_dict = collections.OrderedDict(sorted(initial.items(), key=lambda t: t[0])) print(ordered_dict) OrderedDict([('a', 1), ('b', 2), ('c', 2), ('d', 1), ('e', 3)]) I want to have some function along the vein of... select = int(input("Input dictionary index")) #User inputs 2 #Program looks up the 2nd entry in ordered_dict (c in this case) #And then returns the

Difference between dictionary and ordereddict in python

杀马特。学长 韩版系。学妹 提交于 2019-12-04 19:13:04
问题 I am trying to get a sorted dictionary. But the order of the items between mydict and orddict doesn't seem to change. from collections import OrderedDict mydict = {'a':1,'b':2,'c':3,'d':4} orddict = OrderedDict(mydict) print(mydict,orddict) # print items in mydict: print('mydict') for k,v in mydict.items(): print(k,v) print('ordereddict') # print items in ordered dictionary for k,v in orddict.items(): print(k,v) # print the dictionary keys # for key in mydict.keys(): # print(key) # print the

How do you get the first 3 elements in Python OrderedDict?

只愿长相守 提交于 2019-12-04 18:37:21
问题 How do you get the first 3 elements in Python OrderedDict? Also is it possible to delete data from this dictionary. For example: How would I get the first 3 elements in Python OrderedDict and delete the rest of the elements? 回答1: Let's create a simple OrderedDict : >>> from collections import OrderedDict >>> od = OrderedDict(enumerate("abcdefg")) >>> od OrderedDict([(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g')]) To return the first three keys , values or items

change key in OrderedDict without losing order

强颜欢笑 提交于 2019-12-04 15:48:18
问题 Starting with OrderedDict([('a', 1), ('c', 3), ('b', 2)]) is it possible to end up with OrderedDict([('a', 1), ('__C__', 3), ('b', 2)]) making sure that the '__C__' item is before 'b' and after 'a' i.e. keeping order? 回答1: You could try: >>> d = OrderedDict([('a', 1), ('c', 3), ('b', 2)]) >>> d OrderedDict([('a', 1), ('c', 3), ('b', 2)]) >>> d2 = OrderedDict([('__C__', v) if k == 'c' else (k, v) for k, v in d.items()]) >>> d2 OrderedDict([('a', 1), ('__C__', 3), ('b', 2)]) 回答2: if you wish to

How to subclass an OrderedDict?

我们两清 提交于 2019-12-04 09:55:45
问题 Subclassing a Python dict works as expected: >>> class DictSub(dict): ... def __init__(self): ... self[1] = 10 ... >>> DictSub() {1: 10} However, doing the same thing with a collections.OrderedDict does not work: >>> import collections >>> class OrdDictSub(collections.OrderedDict): ... def __init__(self): ... self[1] = 10 ... >>> OrdDictSub() (…) AttributeError: 'OrdDictSub' object has no attribute '_OrderedDict__root' Thus, the OrderedDict implementation uses a private __root atribute, which

Why can't I create a default, ordered dict by inheriting OrderedDict and defaultdict?

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-04 01:28:09
My first attempt to combine the features of two dictionaries in the collections module was to create a class that inherits them: from collections import OrderedDict, defaultdict class DefaultOrderedDict(defaultdict, OrderedDict): def __init__(self, default_factory=None, *a, **kw): super().__init__(default_factory, *a, **kw) However, I cannot assign an item to this dictionary: d = DefaultOrderedDict(lambda: 0) d['a'] = 1 Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib64/python3.3/collections/__init__.py", line 64, in __setitem__ self.__map[key] = link =

Sorting a nested OrderedDict by key, recursively

夙愿已清 提交于 2019-12-04 00:05:50
Say orig is an OrderedDict which contains normal string:string key value pairs, but sometimes the value could be another, nested OrderedDict . I want to sort orig by key, alphabetically (ascending), and do it recursively . Rules: Assume key strings are unpredictable Assume nesting can take place infinitely, e.g. level 1-50 all have both strings, OrderedDicts, etc as values. Need an assist with the sorted algorithm: import string from random import choice orig = OrderedDict(( ('a', choice(string.digits)), ('b', choice(string.digits)), ('c', choice(string.digits)), ('special', OrderedDict(( ('a'

How to turn pandas dataframe row into ordereddict fast

大憨熊 提交于 2019-12-03 22:52:38
Looking for a fast way to get a row in a pandas dataframe into a ordered dict with out using list. List are fine but with large data sets will take to long. I am using fiona GIS reader and the rows are ordereddicts with the schema giving the data type. I use pandas to join data. I many cases the rows will have different types so I was thinking turning into a numpy array with type string might do the trick. Unfortunately you can't just do an apply (since it fits it back to a DataFrame): In [1]: df = pd.DataFrame([[1, 2], [3, 4]], columns=['a', 'b']) In [2]: df Out[2]: a b 0 1 2 1 3 4 In [3]:

What is the best data structure in .NET for look-up by string key or numeric index?

梦想与她 提交于 2019-12-03 15:01:38
I'm looking for the most ideal data structure (for performance and ease of use) from which values can be retrieved by string key or index. Dictionary doesn't work because you can't really retrieve by index. Any ideas? You want the OrderedDictionary class. You will need to include the System.Collections.Specialized namespace: OrderedDictionary od = new OrderedDictionary(); od.Add("abc", 1); od.Add("def", 2); od.Add("ghi", 3); od.Add("jkl", 4); // Can access via index or key value: Console.WriteLine(od[1]); Console.WriteLine(od["def"]); There's System.Collections.ObjectModel. KeyedCollection<

Difference between dictionary and ordereddict in python

走远了吗. 提交于 2019-12-03 12:16:24
I am trying to get a sorted dictionary. But the order of the items between mydict and orddict doesn't seem to change. from collections import OrderedDict mydict = {'a':1,'b':2,'c':3,'d':4} orddict = OrderedDict(mydict) print(mydict,orddict) # print items in mydict: print('mydict') for k,v in mydict.items(): print(k,v) print('ordereddict') # print items in ordered dictionary for k,v in orddict.items(): print(k,v) # print the dictionary keys # for key in mydict.keys(): # print(key) # print the dictionary values # for value in mydict.values(): # print(value) An OrderedDict preserves the order