LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Python dict query and assign values problems (https://www.linuxquestions.org/questions/programming-9/python-dict-query-and-assign-values-problems-933896/)

ArthurHuang 03-11-2012 10:18 AM

Python dict query and assign values problems
 
Hi guys, I have python dict query and assign values problems, I defined a dict

key_words_list = {
'key description1':'key1',
'key description2':'key2',
'key description3':'key3',
....
...
...
#about 150 keys
}


Then I'll search keys in inputfile which has the following format:

Key description1 10 30 20
Key description5 10 30 50
Key description7 10 30 50
Key description2 14 33 20
Key description4 15 30 50
Key description3 3 30 30
Key description6 10 30 50
Key description8 10 30 80

Now my question is
1)Can I use value in dic as arrray?
For example, can I write codes like this?
for i, key, value in key_words_list:
values[i] = 'some words'
2) If 1st answer is yes, this program can be written in C/C++ style

for line in lines:
for key,value in key_words_list:
if line.startwith(key)
value[0] = "word1"
value[1] = "word2"

BUT, is there any better pythonic style to implement this functionality?

Thanks a lot!!!

ntubski 03-12-2012 10:39 PM

Quote:

Originally Posted by ArthurHuang (Post 4624056)
1)Can I use value in dic as arrray?

Dictionaries don't have a defined order, if that's what you're asking. You can get a copy of the dictionary's contents as an array of (key, value) pairs (see dict.items()), or an array of just the values, or an array of the keys.

Quote:

2) If 1st answer is yes, this program can be written in C/C++ style

for line in lines:
for key,value in key_words_list:
if line.startwith(key)
value[0] = "word1"
value[1] = "word2"

BUT, is there any better pythonic style to implement this functionality?
It's really not clear what functionality you are looking for.

PS please put [code][/code] tags around your code,especially python code.

graemef 03-13-2012 04:18 AM

It's really not clear what it is you are trying to do. If you are stepping through each line in you input file and looking for the entry in you dict then once you have the line from you input file split into a key and value and are ready to see if their is a match with an entry in you dict then you can try:

Code:

if key in key_words_list:
    key_words_list[key] = value

or whatever it is that you want to do with your data.


All times are GMT -5. The time now is 12:20 AM.