python中字典,没键加键,有键操作其键对应的值,的思想

时间:2021-01-10 15:13:27
cars = ['鲁A32444', '鲁B12333', '京B8989M', '黑C49678', '黑C46555', '沪B25041', '黑C34567']
locations = {'': '上海', '': '北京', '': '黑龙江', '': '山东', '': '湖北', '': '湖南'}
# 构建此数据类型{'山东': 2, '北京': 1, '黑龙江': 3, '上海': 1}

# 方法一
dic = {}
for i in cars:
    if locations[i[0]] in dic:
        dic[locations[i[0]]] += 1
    else:
        dic[locations[i[0]]] = 1
print(dic)

# 方法二
dic = {}
for i in cars:
    # get方法,如果有键返回该键对应的值,如果没键,可以设置返回值
    dic[locations[i[0]]] = dic.get(locations[i[0]], 0) + 1
print(dic)
list3 = [
    {"name": "a", "hobby": "抽烟"},
    {"name": "a", "hobby": "喝酒"},
    {"name": "a", "hobby": "烫头"},
    {"name": "wu", "hobby": "喊麦"},
    {"name": "wu", "hobby": "街舞"},
]
# 构建数据类型 list4 = [{"name": "a", "hobby_list": ["抽烟", "喝酒", "汤头"]}]
# 思想:如果没键就添加键,如果有键就操作此键对应的值
# 方法一
list4 = []
for i in list3:
    # print(i)
    for j in list4:
        if i['name'] == j['name']:  # i['name']='a'
            j['hobby_list'].append(i['hobby'])
            break
    else:
        list4.append({'name': i['name'], 'hobby_list': [i['hobby']]})
print(list4)
li = [11, 22, 33, 44, 55, 77, 88, 99, 90]
# 构建数据类型{'key1': [11, 22, 33, 44, 55], 'key2': [77, 88, 99, 90]}
# key1对应的小于60的值,key2对应大于60的值
result = {}
for i in li:
    if i < 66:
        if 'key1' not in result:
            result['key1'] = []
        result['key1'].append(i)
    else:
        if 'key2' not in result:
            result['key2'] = []
        result['key2'].append(i)
print(result)