python常用代码范例_python常用字典操作范例

# experimenting with the Python dictionary

# a seemingly unordered set of key:value pairs, types can be mixed

# Python23 tested vegaseat 13feb2005

# initialize a dictionary, here a dictionary of roman numerals

romanD = {'I':1,'II':2,'III':3,'IV':4,'V':5,'VI':6,'VII':7,'VIII':8,'IX':9}

print "A dictionary is an unordered set of key:value pairs:"

print romanD

# create an empty dictionary

D1 = {}

# show empty dictionary contents and length (number of item/pairs)

print "Empty Dictionary contains:"

# shows {}

print D1

# shows Length = 0

print "Length = ", len(D1)

# add/load new key:value pairs by using indexing and assignment

# here 'eins' is the key, 'one' is the key value

# the start of a german to english dictionary

D1['null'] = 'zero'

D1['eins'] = 'one'

D1['zwei'] = 'two'

D1['drei'] = 'three'

D1['vier'] = 'four'

# print loaded dictionary and length

# the dictionary key order allows for most efficient searching

print "Dictionary now contains (notice the seemingly random order of pairs):"

print D1

print "Length = ",len(D1)

# find the value by key (does not change dictionary)

print "The english word for drei is ", D1['drei']

# better

if 'drei' in D1:

print "The english word for drei is ", D1['drei']

# create a list of the values in the dictionary

L1 = D1.values()

# the list can be sorted, the dictionary itself cannot

L1.sort()

print "A list of values in the dictionary (sorted):"

print L1

# create a list of dictionary keys

L2 = D1.keys()

L2.sort()

print "A list of the dictionary keys (sorted):"

print L2

# does the dictionary contain a certain key?

if D1.has_key('null'):

print "Key 'null' found!"

else:

print "Key 'null' not found!"

# copy dictionary D1 to D2 (the order may not be the same)

D2 = D1.copy()

print "Dictionary D1 has been copied to D2:"

print D2

# delete an entry

del D2['zwei']

print "Dictionary D2 after 'zwei' has been deleted:"

print D2

# extract the value and remove the entry

# pop() changes the dictionary, use e3 = D2['drei'] for no change

e3 = D2.pop('drei')

print "Extract value for key = 'drei' and delete item from dictionary:"

print e3

print "Dictionary D2 after 'drei' has been popped:"

print D2

print

str1 = "I still miss you baby, but my aim's gettin' better!"

print str1

print "Count the characters in the above string:"

# create an empty dictionary

charCount = {}

for char in str1:

charCount[char] = charCount.get(char, 0) + 1

print charCount

print

if 't' in charCount:

print "There are %d 't' in the string" % charCount['t']

print

str2 = "It has been a rough day. I got up this morning put on a shirt and a"

str2 = str2 + " button fell off. I picked up my briefcase and the handle came off."

str2 = str2 + " Now I am afraid to go to the bathroom."

print str2

print "Count the words in the above string, all words lower case:"

# create a list of the words

wordList = str2.split(None)

# create an empty dictionary

wordCount = {}

for word in wordList:

# convert to all lower case

word = word.lower()

# strip off any trailing period, if needed do other punctuations

if '.' in word:

word = word.rstrip('.')

# load key:value pairs by using indexing and assignment

wordCount[word] = wordCount.get(word, 0) + 1

print wordCount

print

# put keys into list and sort

keyList = wordCount.keys()

keyList.sort()

# display words and associated count in alphabetical order

for keyword in keyList:

print keyword, "=", wordCount[keyword]

# put the dictionary pairs into a list, use the romanD dictionary

romanList = []

for key, value in romanD.items():

# put value first for a meaningful sort

romanList.append((value, key))

romanList.sort()

print "\nThe roman numeral dictionary put into a (value,pair) list then sorted:"

print romanList

print "\nList them as pairs on a line:"

for i in xrange(len(romanList)):

print romanList[i][0],'=', romanList[i][1]

print

# split the romanD dictionary into two lists

print "Splitting the romanD dictionary into two lists:"

romankeyList = []

romanvalueList = []

for key, value in romanD.items():

romankeyList.append(key)

romanvalueList.append(value)

print "Key List:",romankeyList

print "Value List:",romanvalueList

print

# make a dictionary from the two lists

print "Combining the two lists into a dictionary:"

romanD1 = dict(zip(romankeyList, romanvalueList))

print romanD1

# to save a Python object like a dictionary to a file

# and load it back intact you have to use the pickle module

import pickle

print "The original dictionary:"

print romanD1

file = open("roman1.dat", "w")

pickle.dump(romanD1, file)

file.close()

file = open("roman1.dat", "r")

romanD2 = pickle.load(file)

file.close()

print "Dictionary after pickle.dump() and pickle.load():"

print romanD2

print

# let's get rid of some duplicate words

str = "Senator Strom Thurmond dressed as as Tarzan"

print "\nOriginal string:"

print str

print "A list of the words in the string:"

wrdList1 = str.split()

print wrdList1

def uniqueList(anyList):

"""given a list, returns a unique list with the order retained"""

# create an empty dictionary

dic1 = {}

# use a list comprehension statement and the unique feature of a dictionary

return [dic1.setdefault(e,e) for e in anyList if e not in dic1]

# a call to the above function will retain the order of words

wrdList2 = uniqueList(wrdList1)

print "Convert unique list back to string (order retained):"

print " ".join(wrdList2)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SQLAlchemy 是一个 SQL 工具包和对象关系映射(ORM)库,用于 Python 编程语言。它提供了一个高级的 SQL 工具和对象关系映射工具,允许开发者以 Python 类和对象的形式操作数据库,而无需编写大量的 SQL 语句。SQLAlchemy 建立在 DBAPI 之上,支持多种数据库后端,如 SQLite, MySQL, PostgreSQL 等。 SQLAlchemy 的核心功能: 对象关系映射(ORM): SQLAlchemy 允许开发者使用 Python 类来表示数据库表,使用类的实例表示表中的行。 开发者可以定义类之间的关系(如一对多、多对多),SQLAlchemy 会自动处理这些关系在数据库中的映射。 通过 ORM,开发者可以像操作 Python 对象一样操作数据库,这大大简化了数据库操作的复杂性。 表达式语言: SQLAlchemy 提供了一个丰富的 SQL 表达式语言,允许开发者以 Python 表达式的方式编写复杂的 SQL 查询。 表达式语言提供了对 SQL 语句的灵活控制,同时保持了代码的可读性和可维护性。 数据库引擎和连接池: SQLAlchemy 支持多种数据库后端,并且为每种后端提供了对应的数据库引擎。 它还提供了连接池管理功能,以优化数据库连接的创建、使用和释放。 会话管理: SQLAlchemy 使用会话(Session)来管理对象的持久化状态。 会话提供了一个工作单元(unit of work)和身份映射(identity map)的概念,使得对象的状态管理和查询更加高效。 事件系统: SQLAlchemy 提供了一个事件系统,允许开发者在 ORM 的各个生命周期阶段插入自定义的钩子函数。 这使得开发者可以在对象加载、修改、删除等操作时执行额外的逻辑。
SQLAlchemy 是一个 SQL 工具包和对象关系映射(ORM)库,用于 Python 编程语言。它提供了一个高级的 SQL 工具和对象关系映射工具,允许开发者以 Python 类和对象的形式操作数据库,而无需编写大量的 SQL 语句。SQLAlchemy 建立在 DBAPI 之上,支持多种数据库后端,如 SQLite, MySQL, PostgreSQL 等。 SQLAlchemy 的核心功能: 对象关系映射(ORM): SQLAlchemy 允许开发者使用 Python 类来表示数据库表,使用类的实例表示表中的行。 开发者可以定义类之间的关系(如一对多、多对多),SQLAlchemy 会自动处理这些关系在数据库中的映射。 通过 ORM,开发者可以像操作 Python 对象一样操作数据库,这大大简化了数据库操作的复杂性。 表达式语言: SQLAlchemy 提供了一个丰富的 SQL 表达式语言,允许开发者以 Python 表达式的方式编写复杂的 SQL 查询。 表达式语言提供了对 SQL 语句的灵活控制,同时保持了代码的可读性和可维护性。 数据库引擎和连接池: SQLAlchemy 支持多种数据库后端,并且为每种后端提供了对应的数据库引擎。 它还提供了连接池管理功能,以优化数据库连接的创建、使用和释放。 会话管理: SQLAlchemy 使用会话(Session)来管理对象的持久化状态。 会话提供了一个工作单元(unit of work)和身份映射(identity map)的概念,使得对象的状态管理和查询更加高效。 事件系统: SQLAlchemy 提供了一个事件系统,允许开发者在 ORM 的各个生命周期阶段插入自定义的钩子函数。 这使得开发者可以在对象加载、修改、删除等操作时执行额外的逻辑。
Python中,查询结果集与字典相结合的运用范例有很多。 例如,假设有一个学生信息表,记录了学生的姓名、年龄和成绩。我们可以使用字典存储每个学生的信息,并使用列表存储所有学生的信息。 ```python # 学生信息表 students = [ {"姓名": "张三", "年龄": 18, "成绩": 90}, {"姓名": "李四", "年龄": 20, "成绩": 85}, {"姓名": "王五", "年龄": 19, "成绩": 92} ] # 查询所有学生的姓名和成绩 name_scores = {} for student in students: name = student["姓名"] score = student["成绩"] name_scores[name] = score print(name_scores) ``` 运行以上代码,输出结果为: ``` {'张三': 90, '李四': 85, '王五': 92} ``` 通过遍历学生信息表,将每个学生的姓名和成绩加入到字典name_scores中。最终得到一个包含所有学生姓名和成绩的字典。 另外,如果需要查询某个学生的成绩,可以直接通过学生的姓名进行查询。 ```python # 查询某个学生的成绩 name = "李四" score = name_scores.get(name) if score: print(f"{name}的成绩是{score}") else: print(f"{name}的成绩未查询到") ``` 运行以上代码,输出结果为: ``` 李四的成绩是85 ``` 上述例子展示了如何使用查询结果集与字典相结合的方法,对学生信息进行查找和查询。通过字典的键-值对结构,可以方便地存储和查询数据。这种运用范例在实际开发中经常使用,能使代码更加简洁、优雅。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值