开发者

Dictionary Operations... Index / Iterate / Validate

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 = examp开发者_高级运维le.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.


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.


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).


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))


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜