Reading lines from text and converting it into Python nested dictionary
up vote
1
down vote
favorite
So i have the below text as an input file:
A B 1
A C 2
B C 1
B D 3
B E 2
C D 1
C E 2
D E 4
D F 3
E F 3
and i want to store all these values in a nested dictionary in python:
'A': 'B': 1, 'C': 2,
'B': 'C': 1, 'D': 3, 'E': 2,
'C': 'D': 1, 'E': 2,
'D': 'E': 4, 'F': 3,
'E': 'F': 3
This is my code which is reading an input file and trying to convert it into a nested dictionary
inputfile = open("input.txt", "r")
lines = inputfile.readlines()
edges =
for line in lines:
edges.append(line.split())
d =
nn=
for i in edges:
nn.update(i[1]:i[2])
d[i[0]] = nn
index+=1
print(d)
This is my incorrect output
'A': 'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3', 'B': 'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3', 'C': 'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3', 'D': 'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3', 'E': 'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3'
I am looking for a correct if else condition which will update the dict items when the key is same and append if it is different. Thanks in advance.
python python-3.x dictionary
add a comment |
up vote
1
down vote
favorite
So i have the below text as an input file:
A B 1
A C 2
B C 1
B D 3
B E 2
C D 1
C E 2
D E 4
D F 3
E F 3
and i want to store all these values in a nested dictionary in python:
'A': 'B': 1, 'C': 2,
'B': 'C': 1, 'D': 3, 'E': 2,
'C': 'D': 1, 'E': 2,
'D': 'E': 4, 'F': 3,
'E': 'F': 3
This is my code which is reading an input file and trying to convert it into a nested dictionary
inputfile = open("input.txt", "r")
lines = inputfile.readlines()
edges =
for line in lines:
edges.append(line.split())
d =
nn=
for i in edges:
nn.update(i[1]:i[2])
d[i[0]] = nn
index+=1
print(d)
This is my incorrect output
'A': 'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3', 'B': 'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3', 'C': 'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3', 'D': 'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3', 'E': 'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3'
I am looking for a correct if else condition which will update the dict items when the key is same and append if it is different. Thanks in advance.
python python-3.x dictionary
add a comment |
up vote
1
down vote
favorite
up vote
1
down vote
favorite
So i have the below text as an input file:
A B 1
A C 2
B C 1
B D 3
B E 2
C D 1
C E 2
D E 4
D F 3
E F 3
and i want to store all these values in a nested dictionary in python:
'A': 'B': 1, 'C': 2,
'B': 'C': 1, 'D': 3, 'E': 2,
'C': 'D': 1, 'E': 2,
'D': 'E': 4, 'F': 3,
'E': 'F': 3
This is my code which is reading an input file and trying to convert it into a nested dictionary
inputfile = open("input.txt", "r")
lines = inputfile.readlines()
edges =
for line in lines:
edges.append(line.split())
d =
nn=
for i in edges:
nn.update(i[1]:i[2])
d[i[0]] = nn
index+=1
print(d)
This is my incorrect output
'A': 'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3', 'B': 'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3', 'C': 'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3', 'D': 'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3', 'E': 'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3'
I am looking for a correct if else condition which will update the dict items when the key is same and append if it is different. Thanks in advance.
python python-3.x dictionary
So i have the below text as an input file:
A B 1
A C 2
B C 1
B D 3
B E 2
C D 1
C E 2
D E 4
D F 3
E F 3
and i want to store all these values in a nested dictionary in python:
'A': 'B': 1, 'C': 2,
'B': 'C': 1, 'D': 3, 'E': 2,
'C': 'D': 1, 'E': 2,
'D': 'E': 4, 'F': 3,
'E': 'F': 3
This is my code which is reading an input file and trying to convert it into a nested dictionary
inputfile = open("input.txt", "r")
lines = inputfile.readlines()
edges =
for line in lines:
edges.append(line.split())
d =
nn=
for i in edges:
nn.update(i[1]:i[2])
d[i[0]] = nn
index+=1
print(d)
This is my incorrect output
'A': 'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3', 'B': 'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3', 'C': 'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3', 'D': 'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3', 'E': 'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3'
I am looking for a correct if else condition which will update the dict items when the key is same and append if it is different. Thanks in advance.
python python-3.x dictionary
python python-3.x dictionary
edited Nov 11 at 0:35
dawg
57.7k1181152
57.7k1181152
asked Nov 11 at 0:22
Sahil Sood
183
183
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
up vote
1
down vote
accepted
You can do:
di=
with open(fn) as f_in:
for line in f_in:
li=line.split()
di.setdefault(li[0],)[li[1]]=li[2]
>>> di
'A': 'B': '1', 'C': '2', 'B': 'C': '1', 'D': '3', 'E': '2', 'C': 'D': '1', 'E': '2', 'D': 'E': '4', 'F': '3', 'E': 'F': '3'
add a comment |
up vote
0
down vote
You can use recursion with collections.defaultdict
:
import collections
def group(d):
_d = collections.defaultdict(list)
for a, *b in d:
_d[a].append(b)
return a:group(b) if len(b) > 1 else dict(b) if len(b[0]) > 1 else b[0][0] for a, b in _d.items()
content = [i.strip('n').split() for i in open('filename.txt')]
final_result = group(content)
Output:
'A': 'B': '1', 'C': '2', 'B': 'C': '1', 'D': '3', 'E': '2', 'C': 'D': '1', 'E': '2', 'D': 'E': '4', 'F': '3', 'E': 'F': '3'
This will also work on larger input samples:
s = """
A B C D
A C D E
A H I F
B D T G
B F E H
B U F A
"""
content = [i.split() for i in filter(None, s.split('n'))]
print(group(content))
Output:
'A': 'B': 'C': 'D', 'C': 'D': 'E', 'H': 'I': 'F', 'B': 'D': 'T': 'G', 'F': 'E': 'H', 'U': 'F': 'A'
Thank you so much for the quick response and a very informative answer. I am still learning Python basics and this really helped me to understand the concept of recursion.
– Sahil Sood
Nov 11 at 0:54
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53244723%2freading-lines-from-text-and-converting-it-into-python-nested-dictionary%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
1
down vote
accepted
You can do:
di=
with open(fn) as f_in:
for line in f_in:
li=line.split()
di.setdefault(li[0],)[li[1]]=li[2]
>>> di
'A': 'B': '1', 'C': '2', 'B': 'C': '1', 'D': '3', 'E': '2', 'C': 'D': '1', 'E': '2', 'D': 'E': '4', 'F': '3', 'E': 'F': '3'
add a comment |
up vote
1
down vote
accepted
You can do:
di=
with open(fn) as f_in:
for line in f_in:
li=line.split()
di.setdefault(li[0],)[li[1]]=li[2]
>>> di
'A': 'B': '1', 'C': '2', 'B': 'C': '1', 'D': '3', 'E': '2', 'C': 'D': '1', 'E': '2', 'D': 'E': '4', 'F': '3', 'E': 'F': '3'
add a comment |
up vote
1
down vote
accepted
up vote
1
down vote
accepted
You can do:
di=
with open(fn) as f_in:
for line in f_in:
li=line.split()
di.setdefault(li[0],)[li[1]]=li[2]
>>> di
'A': 'B': '1', 'C': '2', 'B': 'C': '1', 'D': '3', 'E': '2', 'C': 'D': '1', 'E': '2', 'D': 'E': '4', 'F': '3', 'E': 'F': '3'
You can do:
di=
with open(fn) as f_in:
for line in f_in:
li=line.split()
di.setdefault(li[0],)[li[1]]=li[2]
>>> di
'A': 'B': '1', 'C': '2', 'B': 'C': '1', 'D': '3', 'E': '2', 'C': 'D': '1', 'E': '2', 'D': 'E': '4', 'F': '3', 'E': 'F': '3'
answered Nov 11 at 0:30
dawg
57.7k1181152
57.7k1181152
add a comment |
add a comment |
up vote
0
down vote
You can use recursion with collections.defaultdict
:
import collections
def group(d):
_d = collections.defaultdict(list)
for a, *b in d:
_d[a].append(b)
return a:group(b) if len(b) > 1 else dict(b) if len(b[0]) > 1 else b[0][0] for a, b in _d.items()
content = [i.strip('n').split() for i in open('filename.txt')]
final_result = group(content)
Output:
'A': 'B': '1', 'C': '2', 'B': 'C': '1', 'D': '3', 'E': '2', 'C': 'D': '1', 'E': '2', 'D': 'E': '4', 'F': '3', 'E': 'F': '3'
This will also work on larger input samples:
s = """
A B C D
A C D E
A H I F
B D T G
B F E H
B U F A
"""
content = [i.split() for i in filter(None, s.split('n'))]
print(group(content))
Output:
'A': 'B': 'C': 'D', 'C': 'D': 'E', 'H': 'I': 'F', 'B': 'D': 'T': 'G', 'F': 'E': 'H', 'U': 'F': 'A'
Thank you so much for the quick response and a very informative answer. I am still learning Python basics and this really helped me to understand the concept of recursion.
– Sahil Sood
Nov 11 at 0:54
add a comment |
up vote
0
down vote
You can use recursion with collections.defaultdict
:
import collections
def group(d):
_d = collections.defaultdict(list)
for a, *b in d:
_d[a].append(b)
return a:group(b) if len(b) > 1 else dict(b) if len(b[0]) > 1 else b[0][0] for a, b in _d.items()
content = [i.strip('n').split() for i in open('filename.txt')]
final_result = group(content)
Output:
'A': 'B': '1', 'C': '2', 'B': 'C': '1', 'D': '3', 'E': '2', 'C': 'D': '1', 'E': '2', 'D': 'E': '4', 'F': '3', 'E': 'F': '3'
This will also work on larger input samples:
s = """
A B C D
A C D E
A H I F
B D T G
B F E H
B U F A
"""
content = [i.split() for i in filter(None, s.split('n'))]
print(group(content))
Output:
'A': 'B': 'C': 'D', 'C': 'D': 'E', 'H': 'I': 'F', 'B': 'D': 'T': 'G', 'F': 'E': 'H', 'U': 'F': 'A'
Thank you so much for the quick response and a very informative answer. I am still learning Python basics and this really helped me to understand the concept of recursion.
– Sahil Sood
Nov 11 at 0:54
add a comment |
up vote
0
down vote
up vote
0
down vote
You can use recursion with collections.defaultdict
:
import collections
def group(d):
_d = collections.defaultdict(list)
for a, *b in d:
_d[a].append(b)
return a:group(b) if len(b) > 1 else dict(b) if len(b[0]) > 1 else b[0][0] for a, b in _d.items()
content = [i.strip('n').split() for i in open('filename.txt')]
final_result = group(content)
Output:
'A': 'B': '1', 'C': '2', 'B': 'C': '1', 'D': '3', 'E': '2', 'C': 'D': '1', 'E': '2', 'D': 'E': '4', 'F': '3', 'E': 'F': '3'
This will also work on larger input samples:
s = """
A B C D
A C D E
A H I F
B D T G
B F E H
B U F A
"""
content = [i.split() for i in filter(None, s.split('n'))]
print(group(content))
Output:
'A': 'B': 'C': 'D', 'C': 'D': 'E', 'H': 'I': 'F', 'B': 'D': 'T': 'G', 'F': 'E': 'H', 'U': 'F': 'A'
You can use recursion with collections.defaultdict
:
import collections
def group(d):
_d = collections.defaultdict(list)
for a, *b in d:
_d[a].append(b)
return a:group(b) if len(b) > 1 else dict(b) if len(b[0]) > 1 else b[0][0] for a, b in _d.items()
content = [i.strip('n').split() for i in open('filename.txt')]
final_result = group(content)
Output:
'A': 'B': '1', 'C': '2', 'B': 'C': '1', 'D': '3', 'E': '2', 'C': 'D': '1', 'E': '2', 'D': 'E': '4', 'F': '3', 'E': 'F': '3'
This will also work on larger input samples:
s = """
A B C D
A C D E
A H I F
B D T G
B F E H
B U F A
"""
content = [i.split() for i in filter(None, s.split('n'))]
print(group(content))
Output:
'A': 'B': 'C': 'D', 'C': 'D': 'E', 'H': 'I': 'F', 'B': 'D': 'T': 'G', 'F': 'E': 'H', 'U': 'F': 'A'
edited Nov 11 at 0:37
answered Nov 11 at 0:27
Ajax1234
39.6k42552
39.6k42552
Thank you so much for the quick response and a very informative answer. I am still learning Python basics and this really helped me to understand the concept of recursion.
– Sahil Sood
Nov 11 at 0:54
add a comment |
Thank you so much for the quick response and a very informative answer. I am still learning Python basics and this really helped me to understand the concept of recursion.
– Sahil Sood
Nov 11 at 0:54
Thank you so much for the quick response and a very informative answer. I am still learning Python basics and this really helped me to understand the concept of recursion.
– Sahil Sood
Nov 11 at 0:54
Thank you so much for the quick response and a very informative answer. I am still learning Python basics and this really helped me to understand the concept of recursion.
– Sahil Sood
Nov 11 at 0:54
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53244723%2freading-lines-from-text-and-converting-it-into-python-nested-dictionary%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown