我需要使用Python得到的文本文件字典元素和我建立這個Python代碼:如何從文本文件字典元素
# -*- coding: utf-8 -*-
user_input = raw_input('Write group name: ')
data_file = open('data.txt', 'r')
d = data_file.read()
print d[user_input]
的data.txt文件:
group1 = {
'jhon',
'sam',
'mees'
}
group2 = {
'212332'
}
group3 = {
'USA',
'UK'
}
但我得到這個錯誤:
Traceback (most recent call last):
File "test.py3", line 7, in <module>
print d[user_input]
TypeError: string indices must be integers, not str
我怎樣才能從data.text
文件中的字典元素?
中的數據文件實際上是一組,而不是一個字典,按您的問題,您可以複製數據的樣本驗證在ipython –