题主你好,
看例子吧:
我先定义一个空字典dic:
dic = {}
向字典中添加键值对是通过:
字典名['键名'] = '值'
这种形式, 下面我向字典中添加一个键为'name', 值为'hello kitty'的这么一个键值对:
dic['name'] = 'hello kitty'
此时字典dic的值就内{}, 变为了{'name': 'hello kitty'}
---
测试截图:
希望可以帮到题主, 欢迎追问
NSDictionary*dic =@{@"8":@"AAAA",
@"2":@"BBBBB",
@"3":@"CCCCCC",
@"1":@"FFFFF"}
NSArray*arrKeys = [dicallKeys]
for ( int i =0i <arrKeys.counti++)
{
NSString*key = arrKeys[i]
NSString*value = [dicvalueForKey:key]
NSLog(@"%@ = %@",key,value)
}
NSLog(@"%zd",dic.count)
// 2
[dicenumerateKeysAndObjectsUsingBlock:^( id key, id obj, BOOL *stop) {
NSLog(@"key = %@ and obj = %@", key, obj)
}]
将一个字典键值添加到另外一个字典中 关键字 setVlue
NSDictionary*dict=@{@"1":@"1",@"2":@"2"}
NSMutableDictionary*myHeader=[[NSMutableDictionaryalloc]init]
[myHeader setValue:@"8"forKey:@"8"]
[myHeader setValue:@"9"forKey:@"9"]
[myHeader setValue:@"10"forKey:@"10"]
[myHeader addEntriesFromDictionary:dict]
可以将 dict 字典的键值对添加到 myHeader 中
如果只是添加一次,>>>
l
=
['01',
'张三']
>>>
dic
=
{}
>>>
dic[l[0]]
=
l[1]
如果有大量的这种二元列表要添加到字典中,那么
>>>
data
=
[['01',
'张三'],
['02',
'李四'],
['03',
'None']]
>>>
dic
=
dict(data)
输入
>>>help(dict)
可以看到如下解释:
dict(iterable)
->
new
dictionary
initialized
as
if
via:
|
d
=
{}
|
for
k,
v
in
iterable:
|
d[k]
=
v
传入参数是二元可迭代对象(二元元组、列表等)时,形成对应键值对
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)