Ordereddictionary and Dictionary

OrderedDictionary and Dictionary

You are doing it wrong. You need not only to insert values sequentially into dictionary, but also remove some elements and see how the order has changed after this. The next code demonstrates this:

OrderedDictionary od = new OrderedDictionary();
Dictionary<String, String> d = new Dictionary<String, String>();
Random r = new Random();

for (int i = 0; i < 10; i++)
{
od.Add("key" + i, "value" + i);
d.Add("key" + i, "value" + i);
if (i % 3 == 0)
{
od.Remove("key" + r.Next(d.Count));
d.Remove("key" + r.Next(d.Count));
}
}

System.Console.WriteLine("OrderedDictionary");
foreach (DictionaryEntry de in od) {
System.Console.WriteLine(de.Key + ", " +de.Value);
}

System.Console.WriteLine("Dictionary");
foreach (var tmp in d) {
System.Console.WriteLine(tmp.Key + ", " + tmp.Value);
}

prints something similar to (OrderedDictionary is always ordered):

OrderedDictionary
key3, value3
key5, value5
key6, value6
key7, value7
key8, value8
key9, value9
Dictionary
key7, value7
key4, value4
key3, value3
key5, value5
key6, value6
key8, value8
key9, value9

What is the need of OrderedDictionary, ListDictionary, and HybridDictionary?`

In a nutshell:

  • Dictionary - Well, a dictionary.

  • ListDictionary - Used for small collections, typically less than 10 items

  • HybridDictionary - Used when the collection size is unknown (switches implementations depending on the size of the collection)

  • OrderedDictionary - The elements of an OrderedDictionary are not sorted by the key, unlike the elements of a SortedDictionary<TKey, TValue> class. You can access elements either by the key or by the index.

Better way to convert OrderedDictionary to Dictionarystring, string

Just two improvements to your code. First, you can use foreach instead of while. This will hide details of GetEnumerator.

Second, you can preallocate required space in the target dictionary, since you know how many items you are going to copy.

using System.Collections.Specialized;
using System.Collections.Generic;
using System.Collections;

class App
{
static void Main()
{
var myOrderedDictionary = new OrderedDictionary();
myOrderedDictionary["A"] = "1";
myOrderedDictionary["B"] = "2";
myOrderedDictionary["C"] = "3";
var dict = new Dictionary<string, string>(myOrderedDictionary.Count);
foreach(DictionaryEntry kvp in myOrderedDictionary)
{
dict.Add(kvp.Key as string, kvp.Value as string);
}
}

}

An alternative approach is using LINQ, to convert dictionary in-place, if you want a new instance
of the dictionary, and not populate some existing one:

using System.Linq;
...
var dict = myOrderedDictionary.Cast<DictionaryEntry>()
.ToDictionary(k => (string)k.Key, v=> (string)v.Value);

How can I initialize an OrderedDictionary from a regular Dictionary in Swift?

You can use init(uniqueKeys:values:) with the regular dictionaries' keys and values:

let regularDict = ["key1": "value1", "key2": "value2"]
// => EITHER {key2=>value2, key1=>value1} OR {key1=>value1, key2=>value2}

var orderedDict = OrderedDictionary<String, String>(
uniqueKeys: regularDict.keys,
values: regularDict.values
)
// => EITHER {key2=>value2, key1=>value1} OR {key1=>value1, key2=>value2}

This will not magically sort anything though, the resulting orderedDict will have key-value entries of same random order as the regularDict. But any future changes to the order will be persistent. For example, you could order by keys of a type conforming to Comparable like this:

orderedEntries.sort(by: { $0.key < $1.key })
// => {key1=>value1, key2=>value2}

Get value of an OrderedDictionary

I think the problem is that by casting to (object) before retrieving the object from the ordered dictionary, the dictionary tries to locate the key based on Object.Equals(). Object.Equals returns true if the boxed long objects have the same reference (i.e. the ReferenceEquals method returns true). If you don't mind using strings instead of longs as keys, I would recommend to do so.

To see in detail what's going wrong with your code, maybe replace the following line

object objectFound = (IfcElement)ifcList[(object)idElt];

with

object objectKey = (object)idElt;
object objectFound = (IfcElement)ifcList[objectKey];

And then look in the immediate Window of the debugger whether objectKey.ReferenceEquals(x) returns true for any x in

ifcList.Keys

How to read ordered dictionary data in R

Here it is, test.csv contain your line in A1, just create a for loop if you have multiple lines:

library(reticulate)

test<-read.csv("D:/test.csv", header = FALSE)

test1<-strsplit(as.character(test$V1), split="", fixed=TRUE)
test1<-paste0(test1[[1]][2:(length(test1[[1]])-1)], collapse = "")

py_run_string("from collections import OrderedDict ")
py_run_string(paste0("od=", as.character(test1)))

items<-py_run_string("od.items()")

Rlist<-items$od #list of items in R

swift Dictionary problem where it needs to be ordered by the key

As jnpdx says, the Dictionary method sorted() returns an array of tuples of type (Key, Value) (So (Date, Int) in your case.)

The Swift standard library doesn't have an ordered dictionary. Again, as mentioned by jnpx, there are frameworks/libraries like the official Swift Collections that offer ordered dictionaries. You might want to use one of those.

Alternatively, you could sort the keys from your dictionary and use those to index into your contents.

Using an ordered dict as object dictionary in python

The closest answer to your question that I can find is at http://mail.python.org/pipermail/python-bugs-list/2006-April/033155.html.

Basically, if __dict__ is not an actual dict(), then it is ignored, and attribute lookup fails.

The alternative for this is to use the odict as a member, and override the getitem and setitem methods accordingly.

>>> class A(object) :
... def __init__(self) :
... self.__dict__['_odict'] = odict()
... def __getattr__(self, value) :
... return self.__dict__['_odict'][value]
... def __setattr__(self, key, value) :
... self.__dict__['_odict'][key] = value
...
>>> a = A()
>>> a
<__main__.A object at 0xb7bce34c>
>>> a.x = 1
>>> a.x
1
>>> a.y = 2
>>> a.y
2
>>> a.odict
odict.odict([('x', 1), ('y', 2)])

OrderedDictionary key name at specified index

Use the .Keys collection:

$orderedHash = [ordered] @{ foo = 1; bar = 2 }

# Note the use of @(...)
@($orderedHash.Keys)[0] # -> 'foo'

Note:

  • Use of @(...), the array-subexpression operator, enumerates the .Keys collection and collects its elements in an [object[]] array, which enables access by positional indices.

    • The .Keys collection itself implements only the System.Collections.ICollection interface, which supports enumeration, but not indexed access.

    • @(...) to enable indexing will no longer be necessary in PowerShell (Core) 7.3+ (.NET 7+), thanks to an improvement initiated by iRon via GitHub issue #56835: The .Keys collection will then implement the System.Collections.IList interface, which does support positional indexing. Note that this change will only apply to ordered hashtables ([ordered] @{ ... }, System.Collections.Specialized.OrderedDictionary), not also to regular (unordered) hashtables (@{ ... }) or other types implementing the System.Collections.IDictionary interface. However, iRon has created a follow-up proposal to make the .Keys property indexable for all (definition-)ordered and sorted dictionaries - see GitHub issue #63537.

  • .Name is an alias property provided by PowerShell; the type-native property containing each System.Collections.DictionaryEntry's key is .Key



Related Topics



Leave a reply



Submit