Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

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

Posted on 2014-04-15
1
Medium Priority
?
197 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
1 Comment
 
LVL 29

Accepted Solution

by:
pepr earned 2000 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

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Question has a verified solution.

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

The purpose of this article is to demonstrate how we can upgrade Python from version 2.7.6 to Python 2.7.10 on the Linux Mint operating system. I am using an Oracle Virtual Box where I have installed Linux Mint operating system version 17.2. Once yo…
When we want to run, execute or repeat a statement multiple times, a loop is necessary. This article covers the two types of loops in Python: the while loop and the for loop.
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…
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…

604 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