views:

234

answers:

4

I'd like to:

  • Check a key / value at position i
  • Check to see if key / value contains a string
  • delete / store in another variable either the key / value

The equivelant of this Java code:

//Some list...
ArrayList<String> example;
...
//Index into data structure
example.get(i);
//Check for some string...
if (example.get(i).contains("someText")){

    somestuff;

}
//Store in some other variable
exam = example.get(i)

That's what I'm effectively trying to in Java, however I'd like to be able to do that with Python dictionarties however I'm not sure if this is possible, as I find the Python documentation rather hard to read.

+2  A: 

Direct translation (for an ArrayList<String>, you do not want a dictionary, you want a list):

example = ["foo", "bar", "baz"]
str = example[i]
if "someText" in str:
    somestuff()

Get used to the for keyword, though, it's awesome in Python:

for str in example:
    if "someText" in str:
        someStuff()


Here's an example using dictionaries:

fruits = {
    "apple": "red",
    "orange": "orange",
    "banana": "yellow",
    "pear": "green"
}

for key in fruits:
    if fruits[key] == "apple":
        print "An apple is my favorite fruit, and it is", fruits[key]
    else:
        print "A", key, "is not my favorite fruit, and it is", fruits[key]

Iteration using for on a dictionary results in the keys, it's still up to you to index the item itself. As Alex pointed out, we're really off-base answering you with so little information, and it sounds like you're not well-rooted in data structures (dictionaries will probably yield a different order every time you iterate it).

Jed Smith
Yes, I can do it in a list (like your example). However I have to be able to index into a dictionary. Is this not possible then?
day_trader
Yes, it is, but a dictionary needs a key. I'll edit the answer.
Jed Smith
Dictionaries yield the same order every time you iterate it, because they are hash-tables and they are iterated in order or hashes of elements. So when you add new key it might appear anywhere during next iteration, but will appear in the same position each time you iterate through your dictionary. But in general, you shouldn't rely on this behaviour - if you need ordering, consider implementing your own data structure.
Abgan
+4  A: 

Python dictionaries are implemented as hash tables, so there is no intrinsic ordering; therefore, "position i" is a totally nonsensical concept for a dict -- it's like asking for the dict entry that's most yellow, or that least resembles a llama... those concepts just don't apply to dict entries, and "position i" is just as totally inapplicable.

Where does that i come from, i.e., what's the real issue you're trying to solve? If your requirement is to iterate over the dictionary, you do that directly, without the crutch of a "numeric index". Or, if you do need to keep some specific order or other, then you don't use a dict, but rather some different data structure. If you explain exactly the purpose you're trying to address, I'm sure we can help you.

Alex Martelli
Yes, I was using a dictionary wrongly. I was just seeing if it was possible, instead of converting it to a list (which I've just posted a question on). I appreciate the explanation, thank you.
day_trader
A: 

What's nice about Python is that you can try code interactively.

So we create a list which is like a Java List:

>>> mylist = ["python","java","ruby"]
>>> mylist
['python', 'java', 'ruby']

We can get an entry in the list via its index:

>>> mylist[0]
'python'

And use the find function to search for substrings:

>>> mylist[1].find("av")
1
>>> mylist[1].find("ub")
-1

It returns -1 if the string isn't found.

Copying an entry to a new variable is done just how you'd expect:

>>> newvalue = mylist[2]
>>> newvalue
'ruby'

Or we can create a dict which is like a Java Map, storing by key rather than index, but these work very similarly to lists in Python:

>>> mydict = { 'python':'Guido', 'java':'James', 'ruby':'Yukihiro' }
>>> mydict['java']
'James'
>>> othervalue = mydict['ruby']
>>> othervalue
'Yukihiro'
>>> mydict['python'].find('uid')
1
>>> mydict['python'].find('hiro')
-1
>>> mydict['ruby'].find('hiro')
4
Dave Webb
+1  A: 

Yo can do that to reproduce the same behavior that your example in Java.

# Some list
example = {} # or example = dict()
...
# Index into data estructure.
example[example.keys(i)]
# Check for some string...
if example[example.keys(i)] == 'someText' :
    pass
# Store in some other variable...
exam = example[example.keys(i)]
del example[example.keys(i)]
# ...or
exam = example.pop(example.keys(i))
ocell
Why not store the contents directly in the dictionary? Is it a necessity to have several keys pointing to the same contents (forgive me if I missed something there, just curious).
RedGlyph
In the Java example I understand that the programmer wants to access by index not by key. If he/she wants to access by index a solution is find the index in the keys list and get the value of the diccionari by this key. Get keys list -> Get i key -> Get value from dictionary with the i key.Only is an idea!
ocell