Solved

Allow user to choose items in two Python dictionaries to build a third one

Posted on 2014-04-15
1
192 Views
Last Modified: 2014-04-15
Hi there!

I am trying to build a function that compares fields_csv and fields_db and asks the users which value he's like to import.

I've built it with success with lists but I need both values and keys so i've chosen dictionaries for the job.

I thought something similar and read the subject doing exercises on Code Academy but I still can't get how to handle it:

csv_fields = {'name' : 'john', 'surname' : 'white', 'note' : 'new note'}
db_fields = {'name' : 'john', 'surname' : 'white', 'note' : 'old note'}
import_fields = {}

def fields_check(csv_fields, db_fields):
    for csv_key, csv_value in csv_fields.iteritems():
        for db_key, db_value in db_fields.iteritems():
            if csv_value == db_value:
                import_fields[csv_key] = csv_value
            elif csv_value != db_value:
                while True:
                    print ""
                    print "1) Field in csv: " + csv_value
                    print "2) Field in db: " + db_value
                    print ""
                    user_answer = str(raw_input("Which do you want to keep? [1 o 2]: "))
                    print ""
                    if user_answer == "1":
                        import_fields[csv_key] = csv_value
                        print "You dedided to keep the field name: " + csv_key + " with value: " + csv_value
                        break
                    elif user_answer == "2":
                        import_fields[db_key] = db_value
                        print "You dedided to keep the field name: " + db_key + " with value: " + db_value
                        break
            else:
                print "Error!"

fields_check(csv_fields, db_fields)
print import_fields

Open in new window

0
Comment
Question by:ltpitt
1 Comment
 
LVL 29

Accepted Solution

by:
pepr earned 500 total points
ID: 40002567
I guess that both csv and db should do have the same keys, and only the values may differ. If it is the case then you want to loop through all keys, and it does not matter whether you get them from the csv_fields or the db_fields. Then you get the values for the key from both dictionaries. And then ask the user only when the values differ, as you did.

To summarize, you need only one for loop to go through the keys.
csv_fields = {'name' : 'john', 'surname' : 'white', 'note' : 'new note'}
db_fields = {'name' : 'john', 'surname' : 'white', 'note' : 'old note'}
import_fields = {}

def fields_check(csv_fields, db_fields):
    for k in csv_fields:
        csv_value = csv_fields[k]
        db_value = db_fields[k]
        if csv_value == db_value:
            import_fields[k] = csv_value
        elif csv_value != db_value:
            while True:
                print "The key is:", k
                print
                print "1) Field in csv:", csv_value
                print "2) Field in db: ", db_value
                print
                user_answer = raw_input("Which do you want to keep? [1 o 2]: ")
                print
                if user_answer == "1":
                    import_fields[k] = csv_value
                    print "You dedided to keep the field name:", k, 
                    print "with value:", csv_value
                    break
                elif user_answer == "2":
                    import_fields[k] = db_value
                    print "You dedided to keep the field name:", k, "with value:", db_value
                    break
                else:
                    print "Error!"


fields_check(csv_fields, db_fields)
print import_fields

Open in new window

The csv_value can be extracted via .iteritems() as you did in your code to remove the next line. I did not do that to emphasise symmetry.

If the keys may differ in boh dictionaries, it is possible to iterate through the unified set of the keys from both dictionaries. In this case, the value must be extracted via:
    csv_value = csv_fields.get(k, None)

Open in new window

where None is the default value if the key is not in the dictionary.

It is usually better to use the print command with arguments separated by commas. The reason is that if the argument is not a string, it is converted to the string representation automatically by the print. On the other hand the plus operator needs the strings on both sides.

The raw_input() result need not to be converted to str because it already is str.

If the print command is too long, you can spit it to two prints where the first one ends with the trailing comma -- as shown when printing the csv choice. The comma in print adds the separating space automatically.
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Python Hue issue with import 12 81
Python error - Need Help 12 107
Check to see if file is submitted in correct folder 1 47
Python 3.5.2 - Script Help 3 66
"The time has come," the Walrus said, "To talk of many things: Of sets--and lists--and dictionaries-- Of variable kinks-- And why you see it changing not-- And why so strange are strings." This part describes how variables and references (see …
The purpose of this article is to demonstrate how we can use conditional statements using Python.
Learn the basics of modules and packages in Python. Every Python file is a module, ending in the suffix: .py: Modules are a collection of functions and variables.: Packages are a collection of modules.: Module functions and variables are accessed us…
Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…

791 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question