python数据结构之字典

1、python字典的定义

1、用大括号{},以逗号分隔每个键值对,键与值之间用冒号连接

2、键:需要不可变的数据结构,值可以是任意的数据对象

3、字典是无序的,键在字典中必须是唯一,在字典中取值的方式是以键寻找相对应的的值

a = {}
c = dict()
a
{}
c
{}
b = {'a':'hello','c':'you','b':'how'}
a = [1,2,3]
b = ['a','b','c']
d = dict(zip(a,b))
d
{1: 'a', 2: 'b', 3: 'c'}

给字典中的项value赋值
a = {1:23}
a[1] = 3
a
{1: 3}

字典的访问
b
{'a': 'hello', 'c': 'you', 'b': 'how'}
b.get('a')
'hello'
增:
fruits
{'a': 'apple', 'b': 'banana', 'g': 'grape', 'o': 'orange'}
fruits.setdefault('martin',20)
20
fruits.setdefault('a','appleaaa')
'apple'
fruits
{'a': 'apple', 'b': 'banana', 'g': 'grape', 'o': 'orange', 'martin': 20}

fruits.update({3:5})
fruits.update({'a':'appleupdate'})
fruits
{'a': 'appleupdate', 'b': 'banana', 'g': 'grape', 'o': 'orange', 'martin': 20, 3: 5}
2)    setdefault:参数是key和value,如果key不存在,在添加key:value,如果key存在,什么也不做。
3)    update:参数是key和value,不管key存不存在,都变成 key:value的形式。


删除(工作中不常用)
fruits
{'a': 'appleupdate', 'b': 'banana', 'g': 'grape', 'o': 'orange', 'martin': 20, 3: 5}
fruits.pop(3)
5
fruits
{'a': 'appleupdate', 'b': 'banana', 'g': 'grape', 'o': 'orange', 'martin': 20}

改:
1、赋值
2、update

a
{2: 9, 3: 5, 4: 9}
a[0] = 8
a
{2: 9, 3: 5, 4: 9, 0: 8}
a[2] = 8
a
{2: 8, 3: 5, 4: 9, 0: 8}
a.update({3:10})
a
{2: 8, 3: 10, 4: 9, 0: 8}

查
a
{2: 8, 3: 10, 4: 9, 0: 8}
a.get(2)
8
a[0]
8

两种取值的区别:
当key不存在的时候,get不会报错,
通过[key]方式去取值的时候,会报错
字典的遍历
1for item in _dict:
         print itme

2for k,v in a.items():
        print k,v

a = {1:3,5:0,'ss':123}

for item in a:
    print(item)

a = {1:3,5:0,'ss':123}

for k,v in a.items():
    print(k,v)


当把字典当成序列的时候,指的是key组成的序列

超市购物

#coding:gbk
import sys
food_price = {'apple':5, 'orange': 8, 'banana':3, 'beef':40, 'pork':26, 'cocacola':3}

while True:
    try:
        money = int(input('pls input your money: '))
        break
    except:
        print('your input in not conrrect,pls input a number')
        
shooping_list = []

while True:
    print('
 目前可购买的商品:')
    for food,price in food_price.items():
        print(food,price)
        
    if money < min(food_price.values()):
        print('
 sorry,you have not enough money to buy any food
')
        if shooping_list:
            print('
 你已经买了如下商品:
 %s' %shooping_list)
    print('
 你现在有%s,选择一支商品吧' % money)
    
    _choice = input('
 pls input your choice:')
    choice = _choice.strip()
    
    if choice in ['quit','exit','q']:
        print('
 你已经买了如下商品 
 %s' %shooping_list)
        sys.exit()
        
    if  choice not in food_price:
        print('
 你已经买了如下商品
 %s' %shooping_list)
        continue
    
    price = food_price[choice]
    print('
 你选择的商品:%s的价格:%s' %(choice,price))
    
    if money >= price:
        shooping_list.append(choice)
        money = money - price
        print('
你的余额是 %s 
' % money)
    else:
        print('
sorry,买不起,您剩余:%s$, %s 的价格是 %s $, 真穷!' % (money, choice, price))
        

            
原文地址:https://www.cnblogs.com/hellojackyleon/p/8549039.html