ordereddictionary

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

本秂侑毒 提交于 2019-12-03 11:05:15
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? 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 respectively: >>> list(od)[:3] [0, 1, 2] >>> list(od.values())[:3] ['a', 'b', 'c'] >>> list(od.items())[:3] [(0, 'a'

How do I get a key from a OrderedDictionary in C# by index?

孤人 提交于 2019-12-03 10:55:05
问题 How do I get the key and value of item from OrderedDictionary by index? 回答1: There is not a direct built-in way to do this. This is because for an OrderedDictionary the index is the key; if you want the actual key then you need to track it yourself. Probably the most straightforward way is to copy the keys to an indexable collection: // dict is OrderedDictionary object[] keys = new object[dict.Keys.Count]; dict.Keys.CopyTo(keys, 0); for(int i = 0; i < dict.Keys.Count; i++) { Console.WriteLine

change key in OrderedDict without losing order

懵懂的女人 提交于 2019-12-03 09:49:33
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? 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)]) fbstj if you wish to mutate the current dictionary object: def change_key(self, old, new): for _ in range(len(self)): k, v =

How to subclass an OrderedDict?

蹲街弑〆低调 提交于 2019-12-03 04:23:07
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 prevents the subclass OrdDictSub from behaving like the DictSub subclass. Why? How can one inherit

How do I get a key from a OrderedDictionary in C# by index?

人盡茶涼 提交于 2019-12-03 01:22:15
How do I get the key and value of item from OrderedDictionary by index? There is not a direct built-in way to do this. This is because for an OrderedDictionary the index is the key; if you want the actual key then you need to track it yourself. Probably the most straightforward way is to copy the keys to an indexable collection: // dict is OrderedDictionary object[] keys = new object[dict.Keys.Count]; dict.Keys.CopyTo(keys, 0); for(int i = 0; i < dict.Keys.Count; i++) { Console.WriteLine( "Index = {0}, Key = {1}, Value = {2}", i, keys[i], dict[i] ); } You could encapsulate this behavior into a

Last element in OrderedDict

半城伤御伤魂 提交于 2019-12-02 20:09:23
I have od of type OrderedDict . I want to access its most recently added (key, value) pair. od.popitem(last = True) would do it, but would also remove the pair from od which I don't want. What's a good way to do that? Can /should I do this: class MyOrderedDict(OrderedDict): def last(self): return next(reversed(self)) Using next(reversed(od)) is a perfect way of accessing the most-recently added element. The class OrderedDict uses a doubly linked list for the dictionary items and implements __reversed__() , so this implementation gives you O(1) access to the desired element. Whether it is

Iterate over python dictionary to retrieve only required rows

血红的双手。 提交于 2019-12-02 06:19:29
I am getting the data in HTML table format from external source - from xml.etree import ElementTree as ET s = """<table> <tr><th>Release</th><th>REFDB</th><th>URL</th></tr> <tr><td>3.7.3</td><td>12345</td><td>http://google.com</td></tr> <tr><td>3.7.4</td><td>456789</td><td>http://foo.com</td></tr> </table> """ For converting html table to dictionary table = ET.XML(s) rows = iter(table) headers = [col.text for col in next(rows)] for row in rows: values = [col.text for col in row] out = dict(zip(headers, values)) now my expected output is as below given that I will pass the Release version from

Find a given key's value in a nested ordered dict python

拜拜、爱过 提交于 2019-12-02 04:39:20
I am trying to find the value of a given key from a nested OrderedDict. Key points: I don't know how deep this dict will be nested The name of the key I am looking for is constant, it will be somewhere in the dict I would like to return the value of the key called "powerpoint_color" in this example... mydict= OrderedDict([('KYS_Q1AA_YouthSportsTrustSportParents_P', OrderedDict([('KYS_Q1AA', OrderedDict([('chart_layout', '3'), ('client_name', 'Sport Parents (Regrouped)'), ('sort_order', 'asending'), ('chart_type', 'pie'), ('powerpoint_color', 'blue'), ('crossbreak', 'Total')]))])), My initial

Write Python OrderedDict to CSV

a 夏天 提交于 2019-12-01 17:57:26
I have an ordered dictionary that, as one would expect, contains a number of key-value pairs. I need to parse the contents of the ordered dictionary into CSV format, with the keys in the top row and their respective values in the second row. I've got the first row down, but I'm at a loss as to how to write the second row. The values in the OrderedDict are what you'd expect (what it looks like printed out in the terminal): ([(a, 1), (b, 2), (c, 3)]) . Here's what I have: import csv with open("frequencies.csv", "w") as outfile: csvwriter = csv.writer(outfile) csvwriter.writerow(myDict) I tried

Why does the **kwargs mapping compare equal with a differently ordered OrderedDict?

倖福魔咒の 提交于 2019-12-01 15:23:10
According to PEP 468 : Starting in version 3.6 Python will preserve the order of keyword arguments as passed to a function. To accomplish this the collected kwargs will now be an ordered mapping . Note that this does not necessarily mean OrderedDict . In that case, why does this ordered mapping fail to respect equality comparison with Python's canonical ordered mapping type, the collections.OrderedDict : >>> from collections import OrderedDict >>> data = OrderedDict(zip('xy', 'xy')) >>> def foo(**kwargs): ... return kwargs == data ... >>> foo(x='x', y='y') # expected result: True True >>> foo