Reputation: 1538
I have a dictionary called muncounty- the keys are municipality, county. separted by a comma and the value is a zip code
muncounty['mun'+','+'county'] = 12345
My goal is to split the keys at the comma separating the mun and county and only extract the mun.
I have tried
muncounty.keys().split(',')
Upvotes: 0
Views: 11001
Reputation: 79
Well, verbose mode for that:
muncounty = {}
muncounty['mun'+','+'county'] = 12345
muncounty['mun2'+','+'county2'] = 54321
l = []
for i in muncounty:
l.append(i)
muns = []
for k in l:
muns.append(k.split(',')[0])
But dude... this is a really bad way to store mun/countries ;-)
Upvotes: 0
Reputation: 3357
[x.split(',')[0] for x in muncounty.keys()]
But I would recommend to store your key as tuple (municipality, county).
Upvotes: 0
Reputation: 3738
You could use map and a lambda function.
di = {'a.b':1}
map(lambda k: k.split('.'), di.keys())
Upvotes: 0
Reputation: 96258
You need some kind of looping, e.g. a list comprehension:
[key.split(',') for key in muncounty.keys()]
Upvotes: 2
Reputation: 5252
You're question and example code isn't very clear, but I think what you want is this:
for key in muncounty.keys():
mun, county = key.split(',')
Your current code is trying to perform split
on a list
, which you quite rightly point out can't be done. What the code above does is go through each key, and performs the split
on it individually.
Upvotes: 0