Search Results

Search found 2235 results on 90 pages for 'dictionary'.

Page 8/90 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >

  • read the dictionary value from array

    - by ben martin
    CALORIES = \ { 'Beef' : 200, \ 'Chicken' : 140, \ } class Food(): __slots__ = ( 'cal' # Calories ) def mkFood( name ): """Create and return a newly initialized Food item""" result = Food() result.cal = calorie in dict(CALORIES[1]) return result Is that a proper way to the value of the target item in Calories? Like getting 200, 140, such like that. result.cal = calorie in dict(CALORIES[1])

    Read the article

  • Shell halts while looping and 'transforming' values in dictionary (Python 2.7.5)

    - by Gus
    I'm building a program that will sum digits in a given list in a recursive way. Say, if the source list has 10 elements, the second list will have 9, the third 8 and so on until the last list that will have only one element. This is done by adding the first element to the second, then the second to the third and so on. I'm stuck without feedback from the shell. It halts without throwing any errors, then in a couple of seconds the fan is spinning like crazy. I've read quite a few posts here and changed my approach, but I'm not sure that what have so far can produce the results I'm looking for. Thanks in advance: #--------------------------------------------------- #functions #--------------------------------------------------- #sum up pairs in a list def reduce(inputList): i = 0 while (i < len(inputList)): #ref to current and next item j = i + 1 #don't go for the last item if j != len(inputList): #new number eq current + next number newNumber = inputList[i] + inputList[j] if newNumber >= 10: #reduce newNumber to single digit newNumber = sum(map(int, str(newNumber))) #collect into temp list outputList.append(newNumber) i = i + 1 return outputList; #--------------------------------------------------- #program starts here #--------------------------------------------------- outputList = [] sourceList = [7, 3, 1, 2, 1, 4, 6] counter = len(sourceList) dict = {} dict[0] = sourceList print '-------------' print 'Level 0:', dict[0] for i in range(counter): j = i + 1 if j != counter: baseList = dict.get(i) #check function to understand what it does newList = reduce(baseList) #new key and value from previous/transformed value dict[j] = newList print 'Level %d: %s' % (j, dict[j])

    Read the article

  • Compile error while adding items to nested dictionary

    - by anshu
    I am trying to created nested dictionary variable like the below, But I get compile error stating that it needs "}" at line where I am adding items (line #2) to my nested dictionary. What Am I missing here? Thanks. Dim myNestedDictionary As Dictionary(Of String, Dictionary(Of String, Integer)) = New Dictionary(Of String, Dictionary(Of String, Integer))() myNestedDictionary.Add("A", New Dictionary("A", 4)())

    Read the article

  • How to convert aspell dictionary to simple list of words?

    - by rafalmag
    I want to get list of all words from aspell dictionary. I downloaded aspell and aspell polish dictionary, then unziped it using: preunzip pl.cwl I got pl.wl: ... hippie hippies hippiesowski/bXxYc hippika/MNn hippis/NOqsT hippisiara/MnN hippiska/mMN hippisowski/bXxYc ... but they appear with sufix like /bXxYc or /MNn. These suffixes are defined in pl_affix.dat, which looks like ... SFX n Y 5 SFX n a 0 [^ij]a SFX n ja yj [^aeijoóuy]ja SFX n a 0 [aeijoóuy]ja SFX n ia ij [^drt]ia SFX n ia yj [drt]ia ... It is connected to the declination and conjugation. How can I add to the first list all forms (with all corresponding suffixes as defined in .dat file ) ? BTW: I need this list to spell-checker jazzy.

    Read the article

  • Why can't I define a case-insensitve Dictionary in C#?

    - by Edward Tanguay
    This WPF code: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace TestDict28342343 { public partial class Window1 : Window { public Window1() { InitializeComponent(); Dictionary<string, string> variableNamesAndValues = new Dictionary<string, string>(StringComparison.InvariantCultureIgnoreCase); } } } gives me the error: The best overloaded method match for 'System.Collections.Generic.Dictionary.Dictionary(System.Collections.Generic.IDictionary)' has some invalid arguments Yet I find this code example everywhere such as here and here. How can I define a Dictionary whose keys are case-insensitve?

    Read the article

  • python: a way to get an exhaustive, sorted list of keys in a nested dictionary?

    - by saidimu
    exhaustive: - all keys in the dictionary, even if the keys are in a nested dictionary that is a value to a previous-level dictionary key. sorted: - this is to ensure the keys are always returned in the same order The nesting is arbitrarily deep. A non-recursive algorithm is preferred. level1 = { 'a' : 'aaaa', 'level2_1' : {'b': 'bbbbb', 'level3': {'c': 'cccc', 'd': 'dddddd'} }, 'level2_2' : { 'z': 'zzzzzzz' } }

    Read the article

  • Is there an open source immutable dictionary for C#, with fast 'With/Without' methods?

    - by Strilanc
    I'm looking for a proper C# immutable dictionary, with fast update methods (that create a partial copy of the dictionary with slight changes). I've implemented one myself, using zippers to update a red-black tree, but it's not particularly fast. By 'immutable dictionary' I don't just mean readonly or const. I want something that has reasonably fast 'With' and 'Without', or equivalent, methods that return a thing with slight modifications without modifying the original. An example from another language is map in Scala

    Read the article

  • Can't get a List(Of <my class>) from a Dictionary in .NET?

    - by magsto
    I have a Dictionary with key of type UInteger and the value is List(Of Session) where the (Public) class Session contains a couple of variables and a constructor (Public Sub New(...)). Some of the variables in my Session class is: Private count As Integer Private StartDate As Date Private Values As List(Of Integer) and a couple of methods like: Friend Sub Counter(ByVal c as Integer) count += c End Sub There is no problem to add values to the Dictionary: Dim Sessions As New List(Of Session) Dim dict As New Dictionary(Of Integer, Sessions) then some code to fill up a couple of Session objects in Sessions (not shown here) and then: dict.Add(17, Sessions) 'No problem Sessions.Clear() Sessions = dict(17) 'This doesn't return anything! The Sessions object is empty even if the code doesn't returned any error. Is my class Session to compex to be stored in a Dictionary?

    Read the article

  • how to create english language dictionary application with python (django)?

    - by sintaloo
    Hi All, I would like to create an online dictionary application by using python (or with django). It will be similar to http://dictionary.reference.com/. My question is (1) Are there any existing open source python package or modules or application which implements this functionality that I can use or study from? (2) If the answer to the first question is NO. which algorithm should I follow to create such web application? Can I simply use the python built-in dictionary object for this job? so that the dictionary object's key will be the english word and the value will be the explanation. is this OK in term of performance? OR Do I have to create my own Tree Object to speed up the search? or any existing package which handles this job properly? Thank you very much.

    Read the article

  • Dictionary as DataMember in WCF after installing .NET 4.5 [migrated]

    - by Mauricio Ulate
    After installing .NET Framework 4.5 with Visual Studio 2012, whenever I want to obtain the reference from a WCF service, my dictionaries are changed into arrays. For example, Dictionary<int, double> is changed into ArrayOfKeyValueOfintdoubleKeyValueOfintdouble. This happens in both Visual Studio 2012 and 2010 (both Express). I've reviewed my configuration and the dictionary data type in the service reference configuration is System.Collection.Generic.Dictionary. Changing this doesn't make a difference. Reverting to just using Visual Studio 2010 and .NET 4.0 is not an option.

    Read the article

  • Best Practices for serializing/persisting String Object Dictionary entities

    - by Mark Heath
    I'm noticing a trend towards using a dictionary of string to object (or sometimes string to string), instead of strongly typed objects. For example, the new Katana project makes heavy use of IDictionary<string,object>. This approach avoids the need to continually update your entity classes/DTOs and the database tables that persist them with new properties. It also avoids the need to create new derived entity types to support new types of entity, since the Dictionary is flexible enough to store any arbitrary properties. Here's a contrived example: class StorageDevice { public int Id { get; set; } public string Name { get; set; } } class NetworkShare : StorageDevice { public string Path { get; set; } public string LoginName { get; set; } public string Password { get; set; } } class CloudStorage : StorageDevice { public string ServerUri { get; set } public string ContainerName { get; set; } public int PortNumber { get; set; } public Guid ApiKey { get; set; } } versus: class StorageDevice { public IDictionary<string, object> Properties { get; set; } } Basically I'm on the lookout for any talks, books or articles on this approach, so I can pick up on any best practices / difficulties to avoid. Here's my main questions: Does this approach have a name? (only thing I've heard used so far is "self-describing objects") What are the best practices for persisting these dictionaries into a relational database? Especially the challenges of deserializing them successfully with strongly typed languages like C#. Does it change anything if some of the objects in the dictionary are themselves lists of strongly typed entities? Should a second dictionary be used if you want to temporarily store objects that are not to be persisted/serialized across a network, or should you use some kind of namespacing on the keys to indicate this?

    Read the article

  • How to Get Dictionary<int, string> from Linq to XML Anonymous Object?

    - by DaveDev
    Currently I'm getting a list of HeaderColumns from the following XML snippet: <HeaderColumns> <column performanceId="12" text="Over last month %" /> <column performanceId="13" text="Over last 3 months %" /> <column performanceId="16" text="1 Year %" /> <column performanceId="18" text="3 Years % p.a." /> <column performanceId="20" text="5 Years % p.a." /> <column performanceId="22" text="10 Years % p.a." /> </HeaderColumns> from which I create an object as follows: (admitedly similar to an earlier question!) var performancePanels = new { Panels = (from panel in doc.Elements("PerformancePanel") select new { HeaderColumns = (from column in panel.Elements("HeaderColumns").Elements("column") select new { PerformanceId = (int)column.Attribute("performanceId"), Text = (string)column.Attribute("text") }).ToList(), }).ToList() }; I'd like if HeaderColumns was a Dictionary() so later I extract the values from the anonymous object like follows: Dictionary<int, string> myHeaders = new Dictionary<int, string>(); foreach (var column in performancePanels.Panels[0].HeaderColumns) { myHeaders.Add(column.PerformanceId, column.Text); } I thought I could achieve this with the Linq to XML with something similar to this HeaderColumns = (from column in panel.Elements("HeaderColumns").Elements("column") select new Dictionary<int, string>() { (int)column.Attribute("performanceId"), (string)column.Attribute("text") }).ToDictionary<int,string>(), but this doesn't work because ToDictionary() needs a Func parameter and I don't know what that is / how to implement it, and the code's probably wrong anyway! Could somebody please suggest how I can achieve the result I need? Thanks.

    Read the article

  • Save and Load Dictionary from encrypted or unreadable or binary format ?

    - by Prix
    I have a dictionary like the follow: public Dictionary<int, SpawnList> spawnEntities = new Dictionary<int, SpawnList>(); The class being used is as follow: public class SpawnList { public int NpcID { get; set; } public string Name { get; set; } public int Level { get; set; } public int TitleID { get; set; } public int StaticID { get; set; } public entityType Status { get; set; } public int TypeA { get; set; } public int TypeB { get; set; } public int TypeC { get; set; } public int ZoneID { get; set; } public int Heading { get; set; } public float PosX { get; set; } public float PosY { get; set; } public float PosZ { get; set; } } /// <summary>Entity type enum.</summary> public enum entityType { Ally, Enemy, SummonPet, NPC, Object, Monster, Gatherable, Unknown } How could I save this Dictionary to either a binary or encrypted format so I could later Load it again into my application ? My limitation is .Net 3.5 can't use anything higher.

    Read the article

  • LINQ to XML - How to get Dictionary from Anonymous Object?

    - by DaveDev
    Currently I'm getting a list of HeaderColumns from the following XML snippet: <PerformancePanel> <HeaderColumns> <column performanceId="12" text="Over last month %" /> <column performanceId="13" text="Over last 3 months %" /> <column performanceId="16" text="1 Year %" /> <column performanceId="18" text="3 Years % p.a." /> <column performanceId="20" text="5 Years % p.a." /> <column performanceId="22" text="10 Years % p.a." /> </HeaderColumns> </PerformancePanel> from which I create an object as follows: (admitedly similar to an earlier question!) var performancePanels = new { Panels = (from panel in doc.Elements("PerformancePanel") select new { HeaderColumns = (from column in panel.Elements("HeaderColumns").Elements("column") select new { PerformanceId = (int)column.Attribute("performanceId"), Text = (string)column.Attribute("text") }).ToList(), }).ToList() }; I'd like if HeaderColumns was a Dictionary() so later I extract the values from the anonymous object like follows: Dictionary<int, string> myHeaders = new Dictionary<int, string>(); foreach (var column in performancePanels.Panels[0].HeaderColumns) { myHeaders.Add(column.PerformanceId, column.Text); } I thought I could achieve this with the Linq to XML with something similar to this HeaderColumns = (from column in panel.Elements("HeaderColumns").Elements("column") select new Dictionary<int, string>() { (int)column.Attribute("performanceId"), (string)column.Attribute("text") }).ToDictionary<int,string>(), but this doesn't work because ToDictionary() needs a Func parameter and I don't know what that is / how to implement it, and the code's probably wrong anyway! Could somebody please suggest how I can achieve the result I need? Thanks.

    Read the article

  • Using a Predicate as a key to a Dictionary

    - by Tom Hines
    I really love Linq and Lambda Expressions in C#.  I also love certain community forums and programming websites like DaniWeb. A user on DaniWeb posted a question about comparing the results of a game that is like poker (5-card stud), but is played with dice. The question stemmed around determining what was the winning hand.  I looked at the question and issued some comments and suggestions toward a potential answer, but I thought it was a neat homework exercise. [A little explanation] I eventually realized not only could I compare the results of the hands (by name) with a certain construct – I could also compare the values of the individual dice with the same construct. That piece of code eventually became a Dictionary with the KEY as a Predicate<int> and the Value a Func<T> that returns a string from the another structure that contains the mapping of an ENUM to a string.  In one instance, that string is the name of the hand and in another instance, it is a string (CSV) representation of of the digits in the hand. An added benefit is that the digits re returned in the order they would be for a proper poker hand.  For instance the hand 1,2,5,3,1 would be returned as ONE_PAIR (1,1,5,3,2). [Getting to the point] 1: using System; 2: using System.Collections.Generic; 3:   4: namespace DicePoker 5: { 6: using KVP_E2S = KeyValuePair<CDicePoker.E_DICE_POKER_HAND_VAL, string>; 7: public partial class CDicePoker 8: { 9: /// <summary> 10: /// Magical construction to determine the winner of given hand Key/Value. 11: /// </summary> 12: private static Dictionary<Predicate<int>, Func<List<KVP_E2S>, string>> 13: map_prd2fn = new Dictionary<Predicate<int>, Func<List<KVP_E2S>, string>> 14: { 15: {new Predicate<int>(i => i.Equals(0)), PlayerTie},//first tie 16:   17: {new Predicate<int>(i => i > 0), 18: (m => string.Format("Player One wins\n1={0}({1})\n2={2}({3})", 19: m[0].Key, m[0].Value, m[1].Key, m[1].Value))}, 20:   21: {new Predicate<int>(i => i < 0), 22: (m => string.Format("Player Two wins\n2={2}({3})\n1={0}({1})", 23: m[0].Key, m[0].Value, m[1].Key, m[1].Value))}, 24:   25: {new Predicate<int>(i => i.Equals(0)), 26: (m => string.Format("Tie({0}) \n1={1}\n2={2}", 27: m[0].Key, m[0].Value, m[1].Value))} 28: }; 29: } 30: } When this is called, the code calls the Invoke method of the predicate to return a bool.  The first on matching true will have its value invoked. 1: private static Func<DICE_HAND, E_DICE_POKER_HAND_VAL> GetHandEval = dh => 2: map_dph2fn[map_dph2fn.Keys.Where(enm2fn => enm2fn(dh)).First()]; After coming up with this process, I realized (with a little modification) it could be called to evaluate the individual values in the dice hand in the event of a tie. 1: private static Func<List<KVP_E2S>, string> PlayerTie = lst_kvp => 2: map_prd2fn.Skip(1) 3: .Where(x => x.Key.Invoke(RenderDigits(dhPlayerOne).CompareTo(RenderDigits(dhPlayerTwo)))) 4: .Select(s => s.Value) 5: .First().Invoke(lst_kvp); After that, I realized I could now create a program completely without “if” statements or “for” loops! 1: static void Main(string[] args) 2: { 3: Dictionary<Predicate<int>, Action<Action<string>>> main = new Dictionary<Predicate<int>, Action<Action<string>>> 4: { 5: {(i => i.Equals(0)), PlayGame}, 6: {(i => true), Usage} 7: }; 8:   9: main[main.Keys.Where(m => m.Invoke(args.Length)).First()].Invoke(Display); 10: } …and there you have it. :) ZIPPED Project

    Read the article

  • How to bind a complex dictionary to a Gridview in asp.net?

    - by Mehdi
    I've used an early binding of a dictionary<string, string> to a gridview to show Urls Text and its HRef as key-value and it works like a charm. But since I want to replace the dictionary with this one : dictionary<string, LinkInfo> the binding goes wrong! Should I handle some events like as onItemDataBound or something? and the LinkInfo structure is: public struct LinkInfo{ public string href; public bool Enabled; }

    Read the article

  • In C#: How to declare a generic Dictionary with a type as key and an enumeration of that type as val

    - by Marcel
    Hi all, I want to declare a dictionary that stores typed IEnumerable's of a specific type, with that exact type as key, like so: (Edited to follow johny g's comment) private IDictionary<Type, IEnumerable<T>> _dataOfType where T: BaseClass; //does not compile! The concrete classes I want to store, all derive from BaseClass, therefore the idea to use it as constraint. The compiler complains that it expects a semicolon after the member name. If it would work, I would expect this would make the later retrieval from the dictionary simple like: IEnumerable<ConcreteData> concreteData; _sitesOfType.TryGetValue(typeof(ConcreteType), out concreteData); How to define such a dictionary?

    Read the article

  • .NET: efficient way to produce a string from a Dictionary<K,V> ?

    - by Cheeso
    Suppose I have a Dictionary<String,String>, and I want to produce a string representation of it. The "stone tools" way of doing it would be: private static string DictionaryToString(Dictionary<String,String> hash) { var list = new List<String> (); foreach (var kvp in hash) { list.Add(kvp.Key + ":" + kvp.Value); } var result = String.Join(", ", list.ToArray()); return result; } Is there an efficient way to do this in C# using existing extension methods? I know about the ConvertAll() and ForEach() methods on List, that can be used to eliminate foreach loops. Is there a similar method I can use on Dictionary to iterate through the items and accomplish what I want?

    Read the article

  • Which method of adding items to the ASP.NET Dictionary class is more efficient?

    - by ahmd0
    I'm converting a comma separated list of strings into a dictionary using C# in ASP.NET (by omitting any duplicates): string str = "1,2, 4, 2, 4, item 3,item2, item 3"; //Just a random string for the sake of this example and I was wondering which method is more efficient? 1 - Using try/catch block: Dictionary<string, string> dic = new Dictionary<string, string>(); string[] strs = str.Split(','); foreach (string s in strs) { if (!string.IsNullOrWhiteSpace(s)) { try { string s2 = s.Trim(); dic.Add(s2, s2); } catch { } } } 2 - Or using ContainsKey() method: string[] strs = str.Split(','); foreach (string s in strs) { if (!string.IsNullOrWhiteSpace(s)) { string s2 = s.Trim(); if (!dic.ContainsKey(s2)) dic.Add(s2, s2); } }

    Read the article

  • How to delete a Dictionary row that is a Double by using an Int?

    - by Richard Reddy
    Hi, I have a Dictionary object that is formed using a double as its key values. It looks like this: Dictionary<double, ClassName> VariableName = new Dictionary<double, ClassName>(); For my project I have to have the key as the double as I require values like 1.1,1.2,2.1,2.2,etc in my system. Everything in my system works great except when I want to delete all the keys in a group eg all the 1 values would be 1.1,1.2, etc. I can delete rows if I know the full value of the key eg 1.1 but in my system I will only know the whole number. I tried to do the following but get an error: DictionaryVariable.Remove(j => Convert.ToInt16(j.Key) == rowToEdit).OrderByDescending(j => j.Key); Is there anyway to remove all rows per int value by converting the key? Thanks, Rich

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >