I have a txt file like this:
1234 John Smith
2345 Joe Bloggs
12 Matt Kemp
etc.
I also have a copy of the text file with each value like "value". I want to create a dictionary in the form:
['1234': 'John Smith', '2345': 'Joe Bloggs', '12': 'Matt Kemp']
My current code is:
validclubs = {}
with open("validclubs.txt") as f:
for line in f:
(id, club) = line.split()
d[int(id)] = val
print (d)
but with both files I get ValueError: too many values to unpack (expected 2)
.
line.split()
is splitting on the space between the first and last name of the player.
The full syntax is: string.split(separator, maxsplit)
, where maxsplit
specifies how many splits to do.
(id, club) = line.split(maxsplit = 1)
should do the trick. This is also will handle cases where you have one or more middle names as well.
(Unrelated, your dictionary name changes from validclubs
to d
in the loop.)
The problem here is that you unpack from your line.split ()
which will give you a list of three elements (and you unpack just two element) Unpack three elements then concatenate the name and the lastName
validclubs = {}
with open("validclubs.txt") as f:
for line in f:
(id, name, lastName) = line.split()
d[int(id)] = "{} {}".format(name, lastName)
print (d)
If there is more than one case (not always name and last name):
validclubs = {}
with open("validclubs.txt") as f:
for line in f:
myList = line.split()
d[int(myList[0])] = ''.join(myList[1:])
print (d)
@omg's answer (with maxsplit parameters) is maybe the better solution here...i also learn something here;-)
You can use dictionary comprehension with split
, replace
and join
functions to create a dictionary from each line in the validclubs.txt file.
with open("validclubs.txt") as f:
d = {i.split(" ")[0]: " ".join(i.replace("\n", "").split(" ")[1:]) for i in f}
print(d)
Output
{'1234': 'John Smith', '2345': 'Joe Bloggs', '12': 'Matt Kemp'}
here is your code:)
d = {}
with open("test.txt") as f:
for line in f:
(id, name, lastName) = line.split()
d[id] = name + lastName
print (d)
All of the main stuff was covered in other answers, but I just wanted to point out that you use val
to assign the value instead of club
from the previous line. Also you should make sure to strip "/n"
from each line using something like .strip()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.